How to detect C++11 under MSVC for noexcept featur

2019-05-06 19:33发布

问题:

I'm working with a C++ library. The library's minimum requirements are C++03. I'm catching some warnings under Visual Studio 2015 regarding throwing destructors:

... algparam.h(271): warning C4297: 'AlgorithmParametersBase::~AlgorithmParametersBase':
    function assumed not to throw an exception but does
... algparam.h(271): note: destructor or deallocator has
    a (possibly implicit) non-throwing exception specification

The throw was by design in the 1990s when the code was written, but its showing its age now. We are kind of boxed in at the moment because we are not ready for a major version bump. (And its not as bad as it sounds prima fascia because it guards the throw based on uncaught_exception).

I want to remediate the issue by detecting C++ 11, and then adding noexcept(false). I was going to hide it in a macro so the code would compile under both C++03 and C++11.

The following does not work to detect C++11 under Visual Studio 2015. It does not produce the expected compiler error:

#if (__cpluplus >= 201103L)
# error Not C++11
#endif

Additionally, Microsoft does not appear to offer a Predefined Macros for detection of the language features.

How do I detect C++11 under Visual Studio 2015?


Related, I can detect the version of MSVC compiler via _MSC_VER. I think it will be _MSC_VER=1900 for VS2015. But it does not tell me anything about the language features.

Language features are important if the user enlists VS2015, but uses a downlevel C++ standard. Also, I don't have VS2013 to test, so I'm not sure a 1-off string like _MSC_VER=1700 is a good idea. I'd much rather learn if its C++11 or not.


I've run into similar issues on OS X and Linux with Clang and GCC compilers. See, for example, How to guard move constructors for C++03 and C++11? and What differences, if any, between C++03 and C++11 can be detected at run-time? But in this case, I want to detect it via the preprocessor.


Finally, this library does not use Autotools, Cmake or Boost. It has no external dependencies.

回答1:

You can't detect the language version independently of the VS version, because VS does not offer language versioning switches- there's no such thing as VS2015 C++03 mode. The condition you're trying to detect (a downlevel standard with VS2015) does not exist, which handily explains why there is no feature macro to detect it.

Simply detect the VS version and switch off that.