標籤:
static_assert提供一個編譯時間的斷言檢查。如果斷言為真,什麼也不會發生。如果斷言為假,編譯器會列印一個特殊的錯誤資訊。
| 12345678910111213 |
template <typename T, size_t Size>class Vector{ static_assert(Size < 3, "Size is too small"); T _points[Size];}; int main(){ Vector<int, 16> a1; Vector<double, 2> a2; return 0;} |
| 1234567 |
error C2338: Size is too smallsee reference to class template instantiation ‘Vector<T,Size>‘ being compiled with [ T=double, Size=2 ] |
static_assert和type traits一起使用能發揮更大的威力。type traits是一些class,在編譯時間提供關於類型的資訊。在標頭檔<type_traits>中可以找到它們。這個標頭檔中有好幾種class: helper class,用來產生編譯時間常量。type traits class,用來在編譯時間擷取類型資訊,還有就是type transformation class,他們可以將已存在的類型變換為新的類型。
下面這段代碼原本期望只做用於整數類型。
| 12345 |
template <typename T1, typename T2>auto add(T1 t1, T2 t2) -> decltype(t1 + t2){return t1 + t2;} |
但是如果有人寫出如下代碼,編譯器並不會報錯
| 12 |
std::cout << add(1, 3.14) << std::endl;std::cout << add("one", 2) << std::endl; |
程式會列印出4.14和”e”。但是如果我們加上編譯時間斷言,那麼以上兩行將產生編譯錯誤。
| 12345678 |
template <typename T1, typename T2>auto add(T1 t1, T2 t2) -> decltype(t1 + t2){ static_assert(std::is_integral<T1>::value, "Type T1 must be integral"); static_assert(std::is_integral<T2>::value, "Type T2 must be integral"); return t1 + t2;} |
| 1234567891011121314 |
error C2338: Type T2 must be integralsee reference to function template instantiation ‘T2 add<int,double>(T1,T2)‘ being compiled with [ T2=double, T1=int ]error C2338: Type T1 must be integralsee reference to function template instantiation ‘T1 add<const char*,int>(T1,T2)‘ being compiled with [ T1=const char *, T2=int ] |
c++11 : static_assert和 type traits