我想将宏定义为字符串,然后在编译时包含基于字符串比较的代码:
#include <iostream>
#include <string_view>
constexpr bool strings_equal(char const * a, char const * b) {
return std::string_view(a)==b;
}
#define FOO "bar"
int main() {
#if strings_equal( FOO, "bar") == 0
std::cout << "got a bar!" << '\n';
#endif
return 0;
}
用编译
$ g++ -std=c++17 test.cpp -o my_test
给出错误:
test.cpp:12:18: error: missing binary operator before token "("
12 | #if strings_equal( FOO, "bar") == 0
| ^
编辑:
似乎
#if
指令是否在函数内部很重要,因为如果它在函数内部,我们可以用if constexpr (...) { ... }
替换它,但是如果#if
在文件顶层的函数外部则不可能。我忘了在实际代码中提到这种情况。
最佳答案
这样是不可能的。
但是您可以使用像这样的constexpr。
#include <iostream>
#include <string_view>
constexpr bool strings_equal(char const * a, char const * b) {
return std::string_view(a)==b;
}
constexpr auto FOO = "bar";
int main() {
if constexpr (strings_equal( FOO, "bar")) {
std::cout << "got a bar!" << '\n';
}
return 0;
}
Run-able Code
关于c++ - 如何从预处理程序#if指令调用constexpr函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61034260/