1

如何在庫用戶對模板類的模板參數使用錯誤的類型時實現錯誤消息?實現類特徵特化的錯誤消息

TEST.CPP(從here適應)

#include <type_traits> 
template <typename T, typename Enable = void> 
class foo; // Sorry, foo<T> for non-integral type T has not been implemented. 

template <typename T> 
class foo<T, typename std::enable_if<std::is_integral<T>::value>::type> 
{ }; 

int main() 
{ 
    foo<float> x; 
} 

的代碼不編譯,如所預期。但是,只有當用戶使用了錯誤的類型時,我才能使編譯器顯示錯誤。 g++ test.cpp

test.cpp: In function ‘int main()’: 
test.cpp:11:13: error: aggregate ‘foo<float> x’ has incomplete type and cannot be defined 
    foo<float> x; 

問題

錯誤信息:這不打印,我想(Sorry, foo<T> for non-integral type T has not been implemented.

回答

4

static_assert會做的伎倆錯誤消息:

template <typename T, typename Enable = void> 
class foo 
{ 
    static_assert(sizeof(T) == 0, "Sorry, foo<T> for non-integral type T has not been implemented"); 
}; 

Demo

您需要sizeof(T) == 0,因爲static_assert總是被評估,並且需要依賴於T,否則它將始終觸發,即使對於有效的T也是如此。