Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert that C++11 should be used to compile my program?

Tags:

c++

c++11

I want to use some C++11 features in my program. I might have to share my source code with others in future. How do I assert, inside the code, that C++11 should be used to compile my program? An older compiler might throw an error, but I want the user to be informed clearly that C++11 is required.

I'm using the following C++11 features, if that matters:

  • enum with storage size specified
  • std shared pointer

thanks

like image 210
Neha Karanjkar Avatar asked Apr 14 '13 10:04

Neha Karanjkar


3 Answers

You could check that the value of the __cplusplus macro is 201103L or greater:

#if __cplusplus < 201103L
#error This code requires C++11
#endif

C++11 16.8 Predefined macro names:

The following macro names shall be defined by the implementation:

__cplusplus

The name __cplusplus is defined to the value 201103L when compiling a C++ translation unit. (155)

(155) It is intended that future versions of this standard will replace the value of this macro with a greater value. Non-conforming compilers should use a value with at most five decimal digits.

like image 175
NPE Avatar answered Nov 14 '22 07:11

NPE


__cplusplus macro may come handy

#if __cplusplus < 201103L
#error C++11 Required
#endif

Something like this

like image 20
alexrider Avatar answered Nov 14 '22 06:11

alexrider


As it has already been said, the correct solution would be to check for the __cplusplus macro. However, some compilers have a partial support for C++11 features but do not set this macro for the correct value. For example, strongly-typed enumerations are available in g++ since GCC 4.4.0. However, with the option -std=c++11 (and its equivalents), the macro __cplusplus was not set to the good value before GCC 4.7.0 (it was set to 1 instead). That means that some compilers can compile your code but won't if you check for C++11 that way.

If you just need specific features, then I would check for them with Boost.Config which defines a whole set of macros that can be used to check whther your compiler supports the required features. In your case, you would need:

  • BOOST_NO_CXX11_SCOPED_ENUMS for strongly-typed enumerations.
  • BOOST_NO_CXX11_SMART_PTR for std::shared_ptr.
like image 5
Morwenn Avatar answered Nov 14 '22 07:11

Morwenn