简体   繁体   English

用模板定义宏作为变量

[英]define macro with template as variable

i'm trying to use a macro to create some static variables. 我正在尝试使用宏来创建一些静态变量。

my problem is, how do i do define a macro with 2 parameters, the first is a template and the second a static variable. 我的问题是,如何定义具有2个参数的宏,第一个是模板,第二个是静态变量。 the template should have more than 1 type. 模板应具有1种以上的类型。

for example: 例如:

#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;
}

and is it even possible to do this? 甚至有可能做到这一点?

here is the error: 这是错误:

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 '}'

inspired by 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 约阿希姆

It's because the preprocessor that handles macros is quite stupid. 这是因为处理宏的预处理器非常愚蠢。 It sees five arguments in the second macro "call", the first one being std::pair<int and the second one int> . 它在第二个宏“ call”中看到五个参数,第一个为std::pair<int ,第二个为int> You can't have macro arguments that contains comma. 您不能有包含逗号的宏参数。

You might want to look into variadic macros , and re-arrange so that the class is last in the macro. 您可能需要查看可变参数宏 ,然后重新排列,使类位于宏的最后。

It's not really a solution but merely a work-around: 这并不是真正的解决方案,而只是一种解决方法:

#define COMMA ,

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

or a little bit more readable: 或更具可读性:

#define wrap(...) __VA_ARGS__

macro(wrap(std::pair<int, int>), first_type, test2, 4)

There are a couple of ways to get rid of that top-level comma. 有两种方法可以消除该顶级逗号。

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)

Incidentally, I'd leave off the ; 顺便说一句,我会放弃; from the macro, and use it wherever the macro is used. 从宏开始,并在使用宏的任何地方使用它。 That makes the code look more natural. 这使代码看起来更自然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM