c++11 : static_assert和 type traits

來源:互聯網
上載者:User

標籤:

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.