预处理器检查 constexpr const char* 函数
Preprocessor check constexpr const char* function
我正在使用新版本的库,该库将其版本作为static constexpr const char*
函数提供。我在测试时在新旧版本之间切换,并希望将仅在 6.0 版中编译的代码包装在预处理器检查中
下面我模拟了库如何显示版本号以及我尝试检测它是否以'6'
开头:
#include <iostream>
// This comes from a library
static constexpr const char* VersionNumber() { return "6.0"; }
// This would be my intended method of detecting the version number
static constexpr bool isVersionSix() { return VersionNumber()[0] == '6'; }
int main() {
std::cout << "Code for any versionn";
#if isVersionSix()
std::cout << "Additional code for version 6.0n";
#endif
return 0;
}
不幸的是,这是一个编译器错误:
foo.cpp:12:17: error: missing binary operator before token "("
#if isVersionSix()
我该如何解决这个问题?附带说明一下,我认为检查'6'
而不是"6.0"
对 SO 来说会更容易,如果可以编译,那么制作constexpr
字符串比较函数应该不是问题
我该如何解决这个问题?
选项 1
您可以在运行时测试版本并调用合适的函数或具有代码块。
int main() {
std::cout << "Code for any versionn";
if ( isVersionSix() )
{
std::cout << "Additional code for version 6.0n";
}
return 0;
}
选项 2
如果无法选择在运行时进行分支,则可以使用函数模板,该模板适用于以前的版本,并对版本 6.0 执行某些操作。
template <bool>
void doSomething()
{
// Do nothing
}
// Specialization of the function template
template <> void doSomething<true>()
{
std::cout << "Additional code for version 6.0n";
}
int main() {
std::cout << "Code for any versionn";
doSomething<isVersionSix()>();
return 0;
}
如果可以升级到 GCC 7,则可以使用 if constexpr
,如下所示:
#include <iostream>
// This comes from a library
static constexpr const char* VersionNumber() { return "6.0"; }
// This would be my intended method of detecting the version number
static constexpr bool isVersionSix() { return VersionNumber()[0] == '6'; }
int main() {
std::cout << "Code for any versionn";
if constexpr (isVersionSix()) {
std::cout << "Additional code for version 6.0n";
}
return 0;
}
(现场示例)
如果你没有它,你可以说它甚至不会编译版本 6 的东西,因为即使在-O0
上,如果你更改版本号,它甚至不会将"Additional code for version 6.0n"
放入编译的程序中。
,您可能希望改进版本检查功能。例如,如果库转到版本 7,您的代码将不再有效;您可能需要更新以检查版本是否大于 6 而不是等于 6。但是,如果您这样做,请注意您不会在版本 10 上遇到问题。
相关文章:
- 将char*传递给pthread_read函数
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 从函数返回const char*数组
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 使用c#访问c++dll中带有char*参数的函数时发生AccessViolationException
- 将函数参数"const char*"转换为"std::string_view"是
- std::string 构造函数如何处理固定大小的 char[]?
- 在 constexpr 构造函数 (c++17) 中赋值到 const char * 在使用 Android NDK 时
- 构造函数 (C++) 中的 char 指针参数存在问题
- c ++ 如何在构造函数中初始化 char
- C++ 存储来自 char* 函数的字符列表
- 从循环返回char函数数据
- 预处理器检查 constexpr const char* 函数
- 如何使const char*函数起作用
- 返回一个带有随机选项和局部变量的 char 函数
- System::字符串到char*函数.内存泄漏
- 如何在c++中使用递归char *函数来反转字符串
- 如何在c++中创建一个char函数
- Windows与UTF-16一起使用char*函数
- c++在char函数中搜索char