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

标签 c++ c-preprocessor

<分区>

我有一些看起来像这样的 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-stirng(而不是 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);
                    ^~~~~~~~~~~~~~~~~

关于c++ - 检查预处理器宏是否为 C 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29595001/

相关文章:

c++ - 如何派生/扩展递归类

c++ - 是否有可能我有一个类的前向声明,而不是在头文件中使它们成为引用或指针

C++ 确定是否在不定义预处理器符号的情况下使用调试符号进行编译

c++ - 如果构建和销毁了许多 vector<T> ,自定义分配器是否会提高性能?

c++ - FFmpeg 使用 avcodec_decode_video2 解码原始缓冲区

c++ - 为什么 C/C++ 预处理器在这里添加一个空格?

c - 调用函数的宏

c - 预处理器 : Concatenate string to each argument in __VA_ARGS__

macros - #if 0 作为定义

c++ - Clang 预处理器从 C++ 文件中去除注释