c++ - 将模板定义为变量的宏

标签 c++ templates c-preprocessor

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

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

例如:

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

谢谢约阿希姆

最佳答案

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

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

关于c++ - 将模板定义为变量的宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15341861/

相关文章:

C++:赋值运算符后的 Post++ 运算符重载

c++ - 删除对模板函数的永不运行调用,在运行时获取分配错误

c++ - 无法访问 C 中的#defined 常量

c - 当预处理器处理预处理器行时会发生什么? - '.i' 文件

c++ - sleep 线程和构造函数中的线程初始化

c++ - 使用指向 "this"的 volatile 指针的此模式的目的是什么?

c++ - 快速内存分配/范围问题

c++ - 用于格式化的字符串参数与模板参数

c++ - 此 C++ 运行时警告的含义是什么

c - 如何从 C 代码生成#define 值列表?