當且僅當模板變量的默認特化被實例化時,是否有可能獲得編譯時錯誤?例如如何在編譯時如果實例化模板變量專業化失敗?
template<typename T>
constexpr int foo = /* Something that fails */;
template<>
constexpr int foo<bool> = 42;
// ...
int bar = foo<bool>; // All good!
int meow = foo<int>; // Error if and only if this line exists
所有我試圖把在/* Something that fails*/
已經結束以失敗告終,即使專業化不是實例。這可能嗎?更好的是,如果可以通過像static_assert
這樣的機制以某種方式報告錯誤,那麼它至少有點清晰。
不幸的是,clang並沒有如此放縱:'錯誤:const類型'const int'對象的默認初始化(即使沒有在任何地方引用)。 – Trillian
如何:template constexpr int foo = std :: enable_if :: value> :: type(); –