用模板定义宏作为变量

define macro with template as variable

本文关键字:变量 定义      更新时间:2023-10-16

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

我的问题是,我如何定义一个宏与2个参数,第一个是模板和第二个静态变量。模板应该有一个以上的类型。

例如

:

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

thx Joachim

这不是一个真正的解决方案,而只是一个变通:

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

这是因为处理宏的预处理器相当愚蠢。它在第二个宏"call"中看到五个参数,第一个是std::pair<int,第二个是int>。宏参数不能包含逗号

您可能想要查看可变宏,并重新排列,以便类在宏中的最后。

有几种方法可以去掉顶部的逗号。

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)
顺便说一句,我会从宏中删除;,并在使用宏的任何地方使用它。这使得代码看起来更自然。