用模板定义宏作为变量
define macro with template as variable
我正在尝试使用宏来创建一些静态变量。
我的问题是,我如何定义一个宏与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)
顺便说一句,我会从宏中删除;
,并在使用宏的任何地方使用它。这使得代码看起来更自然。
相关文章:
- 用C++中的一个变量定义一个常量
- 变量定义到C++布尔值转换
- 未声明的标识符错误,但变量定义正确 (?)
- C++多线程程序:变量定义为类成员的隔离错误
- 将变量定义为静态时,为什么可以多次定义它
- 初始值设定项列表与构造函数赋值与变量定义
- 如何根据传递给函数的变量定义特征矩阵大小
- C++ 描述如何使用来简化变量定义
- 如何转发声明依赖于变量定义的类,而变体定义又依赖于模板化类?
- 是否修改其声明语句中的变量定义良好
- 使用类的其他成员变量定义类的成员变量数组
- 是否可以通过全局变量定义具有可变参数数的函数中的参数数量
- 元组 std::get() 不适用于变量定义的常量
- 全局使用变量定义和C 声明
- C++变量定义中的易失性类型量词位置
- 将变量定义为数组和正确的语法
- 多个,包括具有变量定义的头文件
- 调用构造函数,并将成员作为参数解析为变量定义
- 逗号分隔变量定义中关系前的序列
- 如何使用命名变量定义常量右值引用参数的默认值