我注意到,當實例化爲typedef
'ed時,類模板中的靜態斷言不會被觸發。應該用typedef觸發static_assert嗎?
#include <type_traits>
template <typename T>
struct test_assert
{
static_assert(std::is_same< T, int >::value, "should fail");
};
typedef test_assert<float> t;
該代碼編譯沒有錯誤。如果我嘗試創建一個實例,然後斷言失敗:
t obj; // error: static assertion failed: "should fail"
最後,如果我false
更換條件,則斷言失敗,即使我不實例化類模板:
template <typename T>
struct test_assert
{
static_assert(false, "always fails");
};
我在gcc-4.5.1和gcc-4.7.0上試過這段代碼。這種行爲是否正常?編譯器在什麼時候驗證靜態斷言?我猜想涉及到兩階段查找,但typedef不應該觸發第二階段?
+1。很好的問題。 :-) – Nawaz