Nik*_*iou 14
你最初可以编译-std=c++14.如果你的gcc(或clang)不符合c ++ 14,那么编译将失败(由于uknown标志):
g++: error: unrecognized command line option '-std=c++14'
Run Code Online (Sandbox Code Playgroud)
关于功能可用性(查询特定功能的存在),您可以执行功能测试.这里可以找到一个示例文档:这一切都归结为使用宏来测试指定功能的可用性(其中您还可以找到要查找的功能).
因此,即使您想使用多个编译器构建,也可以编写这样的代码(下面是天真的例子):
#if __cpp_constexpr
constexpr
#endif
int triple(int k) { return 3*k; } // compiles with c++98 as well
Run Code Online (Sandbox Code Playgroud)
这就是跨平台开发如何克服支持多个编译器及其版本的乐趣(更精细的示例将显示支持gcc中的单向和由于标准实现的不同速度而在cl中的另一种方式)
该__cplusplus宏包含编译器正在使用的C++标准.每个版本的C++都具有此定义的特定值.这些可能(反直觉地)与标准名称不完全匹配,因此您可以使用gcc来确定值是什么.例如:
#include <stdio.h>
int main()
{
printf("%ld\n", __cplusplus);
}
Run Code Online (Sandbox Code Playgroud)
编译如下:
g++ -std=c++98 file.cpp
g++ -std=c++11 file.cpp
g++ -std=c++14 file.cpp
Run Code Online (Sandbox Code Playgroud)
运行时分别给出以下内容:
199711
201103
201300
Run Code Online (Sandbox Code Playgroud)
如果您要查找的值不可用,则可以使用预定义的宏来生成错误.例如:
#if __cplusplus < 201300
#error I require C++14 for this code, so die.
#endif
// ...
Run Code Online (Sandbox Code Playgroud)
然后g++ -std=c++11 file.cpp编译失败.