Is there a preprocessor directive for detecting C++11x support? [duplicate]

不羁岁月 提交于 2019-11-28 06:09:49
James Kanze

__cplusplus should be defined as 199711L in pre-C++11 compilers, 201103L in those suporting C++11. Whether this is much help in practice is another question: most compilers are only halfway there, so shouldn't be defining it as 201103L, even if they support the features you are interested in. And it's not unheard of for a compiler to lie: a compiler which defines it as 199711L and doesn't support export for templates, for example. But there's no standard feature by feature test.

The simplest solution is just not to use any particular new feature until you can be sure that all compilers support it. You have to write and support the fallback code anyway; why maintain two versions. The one exception to this rule might be new features which impact on performance: whether the compiler supports move semantics or not. In such cases, I'd suggest a compiler dependent include file, which you write yourself based on the compiler documentation and personal tests; just because the compiler may document that it supports a specific feature doesn't mean that its support is bug-free. Just create a directory per targeted compiler, put this file there and specify the appropriate -I or /I option in your makefile or project file.

And your tests should be something along the lines of:

#ifdef HAS_MOVE_SEMANTICS
...
#endif

rather than just on the compiler, version or whatever.

You can check the value of the __cplusplus macro. For C++11, it's greater than 199711L.

So something like

#if __cplusplus > 199711L

#endif

The Boost.Config library provides granular preprocessor macros you can use to conditionally compile based on the presence of a given C++11 feature.

(For a compiler, C++11 support need not be an all or nothing proposition. For example, consider how Microsoft cherry picked which C++11 features to include in Visual Studio 2012 based on what they believed would most benefit their customers.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!