【问题标题】:C++ Template in macros宏中的 C++ 模板
【发布时间】: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&lt;typename Ret, typename Arg&gt; using test_type2 = animal&lt;typename argument_type&lt;Ret(Arg)&gt;::type&gt;;,然后在 Pigusing type = test_type2&lt;T, int&gt;;

标签: c++ templates c-preprocessor


【解决方案1】:

我认为你的typename 放错地方了;它必须在argument_type&lt;T(who)&gt;::type 之前,而不是animal&lt;...&gt; 之前:

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()

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-05-18
      • 1970-01-01
      • 2015-05-07
      • 2010-12-04
      • 2018-11-16
      • 2015-10-16
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多