【发布时间】:2015-04-10 04:00:58
【问题描述】:
我已经阅读了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
它编译得很好。在我把它放在 括号内之后,编译器似乎无法识别“::type”。
我该怎么做才能让它发挥作用?
【问题讨论】:
-
使用“/E”生成预处理输出,这样您就可以看到宏被替换为...然后继续修改宏,直到获得您想要的代码。如果这太令人困惑,请先在没有宏的情况下正确编写代码,这样你就有了一个可以努力的目标。
-
我稍微澄清了我的问题。而且我也确实尝试了没有 marco 的代码,它们确实有效。只有当我把它们放入马可时它才会失败。
-
无论如何,在 C++11 中,您可以改为使用
template<typename Ret, typename Arg> using test_type2 = animal<typename argument_type<Ret(Arg)>::type>;,然后在Pig:using type = test_type2<T, int>;
标签: c++ templates c-preprocessor