1. 程式人生 > >C++11 學習筆記-型別推導

C++11 學習筆記-型別推導

auto型別推導

  auto關鍵字主要有兩種用途:  
- 在變數宣告時根據初始化列表表示式自動推斷該變數的型別
- 宣告函式時作為函式返回值的佔位符
注意事項:
- 使用auto宣告的變數必須馬上初始化
- 函式引數和模板引數不能被宣告為auto
- 對於陣列型別,auto關鍵字會推導為指標型別,除非被宣告為引用
- 在結構體中,auto不能用於非靜態變數

struct{
    auto a = 10; //錯誤,不能用於非靜態變數
    static const auto b = 2; //ok
}

template<class T, class U>
void
add(T t, U u) { auto s = t + u; cout << "type of t + u is " << typeid(s).name() << endl; } //函式返回值佔位符,配合decltype使用,返回型別後置語法 template<class T, class U> auto add(T t, U u) -> decltype(t + u) { return t + u; } int main() { // 簡單自動型別推斷 auto a = 123; cout
<< "type of a is " << typeid(a).name() << endl; //int auto s("fred"); cout << "type of s is " << typeid(s).name() << endl; //string // 冗長的型別說明(如迭代器) vector<int> vec; auto iter = vec.begin(); cout << "type of iter is " << typeid
(iter).name() << endl; }

推導規則:
1. 當不宣告為指標或者引用時,auto的推導結果和初始化表示式拋棄引用和CV限定符後型別一致。
2. 當宣告為指標或者引用時,auto的推導結果將保持初始化表示式的CV屬性。

    auto a = 10;
    auto *pa = new auto(a);
    auto **rpa = new auto(&a);
    cout << typeid(a).name() << endl;   // 輸出: int
    cout << typeid(pa).name() << endl;  // 輸出: int *
    cout << typeid(rpa).name() << endl; // 輸出: int **

    int x = 0; 
    auto *a = &x; // a->int*, auto被推導為int
    auto b = &x; //b->int* ,auto被推導為int*
    auto &c = x; // c->int&, auto被推導為int
    auto d = c; //c->int, auto被推導為int  不宣告為指標或者引用時,auto的推導結果和初始化表示式拋棄引用和CV限定符後型別一致
    const auto e = x; //e->const int 
    auto f = e; //e->int
    const auto& g = x; //g->const int&
    auto &h = g; //h->const int&

decltype型別推導

   decltype用來在編譯時推匯出一個變數型別。
decltype(exp)的推導規則:
1、exp是識別符號,類訪問表示式,decltype(exp)和exp型別一致
2、exp是函式呼叫,decltype(exp)與返回值型別一致。
3、其他情況,若exp是一個左值,則decltype(exp)是exp型別的左值引用,否則與exp型別一致。
4、decltype可以保留住表示式的引用以及CV限定符。