在project中,我使用CMake模塊WriteCompilerDetectionHeader來檢測C++ 11功能是否可用。該模塊爲static_assert
等功能生成兼容性實現的文件:如果該功能可用,則爲該功能聲明的宏擴展爲該功能;否則它會擴展到一些退步。C++ 11 constexpr兼容性實現
功能constexpr
沒有兼容性實現。我試圖提供一個,最後實現了一個雙重實現:一個用於constexpr變量,另一個用於constexpr函數。
在cmake的文件:
write_compiler_detection_header(
FILE "${CMAKE_CURRENT_BINARY_DIR}/foo-compilerdetection.h"
PREFIX Foo
COMPILERS
GNU
MSVC
FEATURES
cxx_constexpr
)
在全局頭:
#include "foo-compilerdetection.h"
#ifdef Foo_COMPILER_CXX_CONSTEXPR
# define Foo_CONSTEXPR_FUNCTION constexpr
# define Foo_CONSTEXPR_OBJECT constexpr
#else
# define Foo_CONSTEXPR_FUNCTION inline
# define Foo_CONSTEXPR_OBJECT const
#endif
所以對於constexpr
將與預選賽const
更換和功能將與預選賽inline
替代變量。
這些替換是否合適?其他限定符或組合或限定符是否更適合變量和函數?
'難道這些替代adequat?'這取決於你如何使用那些'constexpr'函數/變量;如果你使用'constexpr'函數的結果作爲模板參數,'inline'不足以支持 –
在C++ 11中,constexpr成員函數也是const。但是,C++ 14並不是這樣。 – Dutow