傳回值 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<