C++使用宏来判断当前编译期支持的C++标准版本的方法
需要注意的是,很多时候,某个编译器的版本并不完整支持某个C++标准,比如Visual Studio 2010 SP1,虽然支持了部分C++ 11的能力,但是依然有很多C++ 11的特性是不支持的。因此单纯通过C++标准的版本号来鉴别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 https://www.cnblogs.com/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