检查预处理器宏是否为 C 字符串?

Check that preprocessor macro is a C-string?

我有一些看起来像这样的 C++ 代码:

std::string DataDirHelper(const std::string& file) {    
  #ifndef CRYPTOPP_DATA_DIR
    return file;
  #else
    std::string dataDir(CRYPTOPP_DATA_DIR);
    ...
  #endif
}

有没有办法测试 CRYPTOPP_DATA_DIR 是 C 型搅拌(而不是 int)?

如果可以,我该怎么做?

最简单的解决方案是:

std::string DataDirHelper(const std::string& file) {    
  #ifndef CRYPTOPP_DATA_DIR
    return file;
  #else
    std::string dataDir("" CRYPTOPP_DATA_DIR);
    ...
  #endif
}

CRYPTOPP_DATA_DIR为字符串字面量时,编译器会将其与相邻的空字符串合并。当它不是字符串文字时,如果宏足够糟糕(有一些前导逗号等等),它仍然可以编译。

或者,我们可以使用 static_assert 需要字符串文字作为参数的要求。因此,我们可以编写这样的代码:

std::string DataDirHelper(const std::string& file) {    
    static_assert(true, CRYPTOPP_DATA_DIR);
    std::string dataDir("" CRYPTOPP_DATA_DIR);
    ...
}

如果 CRYPTOPP_DATA_DIR 不是字符串文字,您会看到如下错误消息:

foo.cc:12:9: error: expected string literal
static_assert(true, CRYPTOPP_DATA_DIR);
                    ^~~~~~~~~~~~~~~~~