C++使用宏來判斷當(dāng)前編譯期支持的C++標(biāo)準(zhǔn)版本的方法
需要注意的是,很多時候,某個編譯器的版本并不完整支持某個C++標(biāo)準(zhǔn),比如Visual Studio 2010 SP1,雖然支持了部分C++ 11的能力,但是依然有很多C++ 11的特性是不支持的。因此單純通過C++標(biāo)準(zhǔn)的版本號來鑒別C++特性是否可用是并不完備的方法。具體支持情況可以參考這里。
#ifdef _MSC_VER #define FL_COMPILER_MSVC 1 #else #define FL_COMPILER_MSVC 0 #endif #ifdef __GNUC__ #define FL_COMPILER_GCC 1 #else #define FL_COMPILER_GCC 0 #endif // __GNUC__ // NOLINT #if FL_COMPILER_MSVC // @reference http://www.rzrgm.cn/bodong/p/18293350 // Each version of Visual Studio does not have complete support for the C++ standard, // so simply judging the feature support of the C++ standard through these version numbers is incomplete. #if _MSC_FULL_VER <= 150030729 // before Visual Studio 2008 sp1, set C++ 98 #define _MSVC_LANG 199711 #elif _MSC_FULL_VER <= 180021114 // before Visual Studio 2013 Nobemver CTP, set C++ 11 #define _MSVC_LANG 201103 #elif _MSC_FULL_VER <= 190023918 // before Visual Studio 2015 Update 2, set C++ 14 #define _MSVC_LANG 201402 #endif // after Visual Studio 2015 Update 3, _MSVC_LANG exists #define FL_COMPILER_LANG_VERSION _MSVC_LANG #elif defined(__cplusplus) #define FL_COMPILER_LANG_VERSION __cplusplus #else // set C++ 98 as default #define FL_COMPILER_LANG_VERSION 199711 #pragma message("No valid C++ standard identification flag found, default to C++98 standard") #endif // is greater than ? // Checks whether the current C++ standard is a later version #define FL_COMPILER_IS_GREATER_THAN_CXX23 (FL_COMPILER_LANG_VERSION >= 202101) #define FL_COMPILER_IS_GREATER_THAN_CXX20 (FL_COMPILER_LANG_VERSION >= 202002) #define FL_COMPILER_IS_GREATER_THAN_CXX17 (FL_COMPILER_LANG_VERSION >= 201703) #define FL_COMPILER_IS_GREATER_THAN_CXX14 (FL_COMPILER_LANG_VERSION >= 201402) #define FL_COMPILER_IS_GREATER_THAN_CXX11 (FL_COMPILER_LANG_VERSION >= 201103) #define FL_COMPILER_IS_GREATER_TAHN_CXX98 (FL_COMPILER_LANG_VERSION >= 199711) // is C++ xx ? // Check whether the current C++ standard specifies a certain version #define FL_COMPILER_IS_CXX23 (FL_COMPILER_LANG_VERSION >= 202101) #define FL_COMPILER_IS_CXX20 (FL_COMPILER_LANG_VERSION >= 202002 && FL_COMPILER_LANG_VERSION < 202101) #define FL_COMPILER_IS_CXX17 (FL_COMPILER_LANG_VERSION >= 201703 && FL_COMPILER_LANG_VERSION < 202002) #define FL_COMPILER_IS_CXX14 (FL_COMPILER_LANG_VERSION >= 201402 && FL_COMPILER_LANG_VERSION < 201703) #define FL_COMPILER_IS_CXX11 (FL_COMPILER_LANG_VERSION >= 201103 && FL_COMPILER_LANG_VERSION < 201402) #define FL_COMPILER_IS_CXX98 (FL_COMPILER_LANG_VERSION >= 199711 && FL_COMPILER_LANG_VERSION < 201103)
可以簡單測試一下:
#if FL_COMPILER_IS_CXX23 #pragma message("C++ 23") #elif FL_COMPILER_IS_CXX20 #pragma message("C++ 20") #elif FL_COMPILER_IS_CXX17 #pragma message("C++ 17") #elif FL_COMPILER_IS_CXX14 #pragma message("C++ 14") #elif FL_COMPILER_IS_CXX11 #pragma message("C++ 11") #elif FL_COMPILER_IS_CXX98 #pragma message("C++ 98") #else #error "can't find C++ compiler version." #endif

浙公網(wǎng)安備 33010602011771號