c++11新特性--decltype

來源:互聯網
上載者:User

傳回值 decltype(運算式)

[傳回值的類型是運算式參數的類型]


這個可也用來決定運算式的類型,就像Bjarne暗示的一樣,如果我們需要去初始化某種類型的變數,auto是最簡單的選擇,但是如果我們所需的類型不是一個變數,例如傳回值這時我們可也試一下decltype。


現在我們回看一些例子我們先前做過的,

[cpp]  view plain  copy template <class U, class V>   void Somefunction(U u, V v)   {       result = u*v;//now what type would be the result???       decltype(u*v) result = u*v;//Hmm .... we got what we want   }  

在下面的一個段落我將會讓你熟悉這個觀念用 auto 和 decltype 來聲明模板函數的傳回值,其類型依靠模板參數。



1. 如果這個運算式是個函數,decltype 給出的類型為函數傳回值的類型。

[cpp]  view plain  copy int add(int i, int j){ return i+j; }   decltype(add(5,6)) var = 5;//Here the type of var is return of add() -> which is int  
2.如果運算式是一個左實值型別,那麼 decltype 給出的類型為運算式左值參考型別。

[cpp]  view plain  copy struct M { double x; };      double pi = 3.14;   const M* m = new M();   decltype( (m->x) ) piRef = pi;          // Note: Due to the inner bracets the inner statement is evaluated as expression,       // rather than member 'x' and as type of x is double and as this is lvale       // the return of declspec is double& and as 'm' is a const pointer        // the return is actually const double&.       // So the type of piRef is const double&  

3.非常重要的標記一下,decltype 不會執行運算式而auto會,他僅僅推論一下運算式的類型。

[cpp]  view plain  copy int foo(){}   decltype( foo() ) x; // x is an int and note that                         // foo() is not actually called at runtime  


跟蹤傳回型別:

這對 C++ 開發人員來說是一個全新的特性,直到現在函數的傳回型別必須放在函數名的前面。到了 C++11,我們也可以將函數傳回值的類型放在函式宣告後,當然僅需要用 auto 替代傳回型別。現在我們想知道怎麼做,讓我們來尋找答案:

[cpp]  view plain  copy template<class U, class V>   ??? Multiply(U u, V v)    // how to specifiy the type of the return value   {       return u*v;   }  
我們明顯的不能像這樣:

[cpp]  view plain  copy template<

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.