C++宏中的模板

C++ Template in macros

本文关键字:C++      更新时间:2023-10-16

我读过关于这个主题的文章。但是当我尝试这样做时,我仍然遇到问题。

template<typename T> struct argument_type;
template<typename T, typename U> struct argument_type<T(U)> { typedef U type; };
#define TEST_TYPE2(who) typename animal < argument_type<T(who)>::type >
template<typename T, typename T2>
struct Pig 
{
    typedef TEST_TYPE2(int) type;
};

我会得到编译错误

warning C4346: 'argument_type<T(int)>::type' : dependent name is not a type
prefix with 'typename' to indicate a type
see reference to class template instantiation 'Pig<T,T2>' being compiled
error C2923: 'animal' : 'argument_type<T(int)>::type' is not a valid template type argument for parameter 'T'

但是,如果我改变

#define TEST_TYPE2(who) typename animal < argument_type<T(who)>::type >

到下面

#define TEST_TYPE2(who) typename argument_type<T(who)>::type

它编译得很好。似乎编译器无法识别"::type",将其放在<>括号内。

我能做些什么来让它工作?

我认为你只是把typename放在错误的地方;它必须在argument_type<T(who)>::type之前,而不是animal<...>之前:

template<typename T> struct animal {};
template<typename T> struct argument_type;
template<typename T, typename U> struct argument_type<T(U)> { typedef U type; };
#define TEST_TYPE2(who) animal<typename argument_type<T(who)>::type>
template<typename T, typename T2> struct Pig {
    typedef TEST_TYPE2(int) type;
};
int main(void) {
    return 0;
} // end main()

上面的编译对我来说很好。

需要使用typename是意料之中的,但请尝试这样做。

#define TEST_TYPE2(who) animal < typename argument_type<T(who)>::type >
相关文章:
  • 没有找到相关文章