宏中的C ++模板

时间:2015-04-10 04:00:58

标签: c++ templates c-preprocessor

我已就此主题阅读了posts。但是当我尝试这样做时,我仍然有问题。

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

编译好。似乎编译器无法识别&#34; :: type&#34;我把它放在&lt;&gt;之后括号中。

我该怎么做才能让它发挥作用?

2 个答案:

答案 0 :(得分:2)

需要使用typename,但请尝试这种方式。

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

答案 1 :(得分:2)

我认为你刚刚把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()

以上编辑对我来说很好。