【问题标题】:define macro with template as variable用模板定义宏作为变量
【发布时间】:2013-03-11 15:03:25
【问题描述】:

我正在尝试使用宏来创建一些静态变量。

我的问题是,我如何定义一个带有 2 个参数的宏,第一个是模板,第二个是静态变量。模板应该有超过 1 种类型。

例如:

#define macro(x, y, z, v) x::y z = v;

int main(int argc, char *argv[]) {
  // this works
  macro(std::queue<int>, value_type, test, 4)
  // this also works
  std::pair<int, int>::first_type x = 3;

  // this is produsing some compiler errors
  macro(std::pair<int, int>, first_type, test2, 4)

  return 0;
}

甚至有可能做到这一点吗?

这是错误:

main.cpp(47) : warning C4002: too many actual parameters for macro 'macro'
main.cpp(47) : error C2589: 'int' : illegal token on right side of '::'
main.cpp(47) : error C2589: 'int' : illegal token on right side of '::'
main.cpp(47) : error C2143: syntax error : missing ',' before '::'
main.cpp(50) : error C2143: syntax error : missing ';' before '}'
main.cpp(51) : error C2143: syntax error : missing ';' before '}'

灵感来自 Joachim Pileborg

#define macro(x, y, z, v, ...) x<__VA_ARGS__>::y z = v;
...

// now it works
macro(std::pair, first_type, test2, 4, int, int)

谢谢约阿希姆

【问题讨论】:

  • 你能粘贴你得到的编译器错误吗?

标签: c++ templates c-preprocessor


【解决方案1】:

这是因为处理宏的预处理器非常愚蠢。它在第二个宏“调用”中看到五个参数,第一个是std::pair&lt;int,第二个是int&gt;。不能有包含逗号的宏参数。

您可能想要查看variadic macros,并重新排列以使该类在宏中的最后一个。

【讨论】:

    【解决方案2】:

    有几种方法可以去掉那个顶级逗号。

    typedef std::pair<int, int> int_pair;
    macro(int_pair, first_type, test2, 4)
    
    macro((std::pair<int, int>), first_type, test2, 4);
    
    #define macro2(x1, x2, y, z, v) x1, x2::y z = v;
    macro2(std::pair<int, int> first_type, test2, 4)
    

    顺便说一句,我会从宏中去掉;,并在使用宏的任何地方使用它。这使代码看起来更自然。

    【讨论】:

      【解决方案3】:

      这并不是真正的解决方案,而只是一种解决方法:

      #define COMMA ,
      
      macro(std::pair<int COMMA int>, first_type, test2, 4)
      

      或者更易读一点:

      #define wrap(...) __VA_ARGS__
      
      macro(wrap(std::pair<int, int>), first_type, test2, 4)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多