mal*_*cot 1 c++ c-preprocessor
我正在尝试同时定义和声明一些全局C++常量:
在constants.h中:
#ifdef DEFINE_CONSTANTS
#define DECLARE_CONSTANT(DECL_, VAL_) extern DECL_ = VAL_
#else
#define DECLARE_CONSTANT(DECL_, VAL_) extern DECL_
#endif
namespace Constants {
DECLARE_CONSTANT(const char LABEL[], "SomeText");
DECLARE_CONSTANT(const int REQUEST_TIMEOUT_MS, 5000);
};
Run Code Online (Sandbox Code Playgroud)
在constants.cpp中:
#define DEFINE_CONSTANTS
#include "constants.h"
#undef DEFINE_CONSTANTS
Run Code Online (Sandbox Code Playgroud)
在使用常量的所有其他文件中,我只包含constants.h
现在,如果我不使用数组初始化器,上面的工作就可以了.但是,当我尝试做类似的事情时:
DECLARE_CONSTANT(const int ARRAY[], {0,1,2});
Run Code Online (Sandbox Code Playgroud)
编译constants.cpp时我得到一个错误,因为初始化程序中的逗号"混淆"预处理器,认为DECLARE_CONSTANT的参数太多(确切的错误取决于编译器).
有没有办法解决这个问题?其他解决方案也欢迎.
这是因为预处理器非常愚蠢,对C或C++的语法或结构一无所知.所以它看作{0,1,2}宏的三个不同的参数.
您可以为此使用可变参数宏:
#define DECLARE_CONSTANT(DECL_, ...) extern DECL_ = __VA_ARGS__
Run Code Online (Sandbox Code Playgroud)