我的代码可以使用define宏进行配置。为了获得代码中的值,我这样做:
#ifdef CONFIG_X
static constexpr bool x = true;
#else
static constexpr bool x = false;
#endif
但是在具有几个配置变量的代码中,这很快变得非常丑陋......
我找到的另一个解决方案就是将代码分成两部分:
#ifdef CONFIG_X
#define CONFIG_X_BOOL true
#else
#define CONFIG_X_BOOL false
#endif
static constexpr bool x = CONFIG_X_BOOL;
这有点好,但也不是很好。
如果定义了宏,是否有一个很好的方法来获得布尔值或1或0?
#ifndef CONFIG_X
#error "Written for config x"
#endif
// True for config x, hack this about for other configurations
static bool x = 1;
现在,如果config不是x,它就会中断。通常,这比试图猜测非X的未命名配置需要的更好。
这是可能的,但仅限于您正在寻找空定义的有限情况(通常是编译标志的情况)或您知道定义标志的方式的范围,例如使用0或1。
这是工作代码:
#include <iostream>
// Define two genetic macros
#define SECOND_ARG(A,B,...) B
#define CONCAT2(A,B) A ## B
// If a macro is detected, add an arg, so the second one will be 1.
#define DETECT_EXIST_TRUE ~,1
// DETECT_EXIST merely concats a converted macro to the end of DETECT_EXIST_TRUE.
// If empty, DETECT_EXIST_TRUE converts fine. If not 0 remains second argument.
#define DETECT_EXIST(X) DETECT_EXIST_IMPL(CONCAT2(DETECT_EXIST_TRUE,X), 0, ~)
#define DETECT_EXIST_IMPL(...) SECOND_ARG(__VA_ARGS__)
// We will create MY_DEFINE, but not MY_DEFINE2
#define MY_DEFINE
int main()
{
// We can now use DETECT_EXIST to detect defines.
std::cout << "MY_DEFINE = " << DETECT_EXIST(MY_DEFINE) << std::endl;
std::cout << "MY_DEFINE2 = " << DETECT_EXIST(MY_DEFINE2) << std::endl;
}
此代码将生成输出:
MY_DEFINE = 1
MY_DEFINE2 = 0
因为第一个确实存在而第二个不存在。
如果将宏设置为诸如1的值,则只需要使用备用版本的DETECT_EXIST_TRUE来处理它,并将宏值粘贴在末尾。例如:
#define DETECT_EXIST_TRUE1 ~,1
如果你有:
#define MY_DEFINE1 1
像这样的代码也可以在main中正常工作:
std::cout << "MY_DEFINE1 = " << DETECT_EXIST(MY_DEFINE1) << std::endl;