您可以在这里使用两个“功能测试”宏:
__has_feature
和__has_extension
这些类似函数的宏采用单个标识符参数,即功能名称。__has_feature
如果 Clang 支持该功能并在当前语言标准中标准化,则__has_extension
评估为 1;如果不支持,则评估为 0,而如果 Clang 在当前语言中支持该功能(作为语言扩展或标准语言功能) ,则评估为 1如果不是,则为 0。
这些宏和标识符记录在这里:
http://clang.llvm.org/docs/LanguageExtensions.html
在您的具体示例中,以下 HelloWorld 提供的信息最多:
#if __has_extension(cxx_generalized_initializers)
#warning __has_extension(cxx_generalized_initializers) is true
#else
#warning __has_extension(cxx_generalized_initializers) is false
#endif
#if __has_feature(cxx_generalized_initializers)
#warning __has_feature(cxx_generalized_initializers) is true
#else
#warning __has_feature(cxx_generalized_initializers) is false
#endif
#if __has_extension(cxx_range_for)
#warning __has_extension(cxx_range_for) is true
#else
#warning __has_extension(cxx_range_for) is false
#endif
#if __has_feature(cxx_range_for)
#warning __has_feature(cxx_range_for) is true
#else
#warning __has_feature(cxx_range_for) is false
#endif
int main()
{
}
对我来说,使用 -std=c++03 它输出:
test.cpp:4:2: warning: __has_extension(cxx_generalized_initializers) is false [-W#warnings]
#warning __has_extension(cxx_generalized_initializers) is false
^
test.cpp:10:2: warning: __has_feature(cxx_generalized_initializers) is false [-W#warnings]
#warning __has_feature(cxx_generalized_initializers) is false
^
test.cpp:14:2: warning: __has_extension(cxx_range_for) is true [-W#warnings]
#warning __has_extension(cxx_range_for) is true
^
test.cpp:22:2: warning: __has_feature(cxx_range_for) is false [-W#warnings]
#warning __has_feature(cxx_range_for) is false
^
4 warnings generated.
而使用 -std=c++11 时,输出变为:
test.cpp:2:2: warning: __has_extension(cxx_generalized_initializers) is true [-W#warnings]
#warning __has_extension(cxx_generalized_initializers) is true
^
test.cpp:8:2: warning: __has_feature(cxx_generalized_initializers) is true [-W#warnings]
#warning __has_feature(cxx_generalized_initializers) is true
^
test.cpp:14:2: warning: __has_extension(cxx_range_for) is true [-W#warnings]
#warning __has_extension(cxx_range_for) is true
^
test.cpp:20:2: warning: __has_feature(cxx_range_for) is true [-W#warnings]
#warning __has_feature(cxx_range_for) is true
^
4 warnings generated.
对于您的用例,您可以在代码为__has_extension(cxx_generalized_initializers)
true 时使用新功能并使用新功能,否则在 false 时解决它。然后,您的代码将在您升级 clang 或使用的语言模式更改时自动适应。
至于支持哪些语言功能,哪些不支持,文档可能会有所帮助,但我发现编写上述测试是评估我当前的 clang 版本的最快和最准确的方法。