c++11 decltype

來源:互聯網
上載者:User

標籤:cto   warning   war   ble   col   ring   out   return   log   

c++11 decltype

decltype實際上有點像auto的反函數,auto可以讓你聲明一個變數,而decltype則可以從一個變數或運算式中得到類型。decltype在C++11標準制定時引入,主要是為泛型程式設計而設計,以解決泛型程式設計中,由於有些類型由模板參數決定,而難以(甚至不可能)表示之的問題。decltype無法在衍生類別聲明和解構函式調用中使用。
類似於sizeof操作符,decltype也不需對其運算元求值。粗略來說,decltype(e)傳回型別前,進行了如下推導: ?

若運算式e指向一個局部變數、命名空間範圍變數、靜態成員變數或函數參數,那麼 傳回型別即為該變數(或參數)的“宣告類型”; ?
若e是一個左值(lvalue,即“可定址值”),則decltype(e)將返回T&,其中T為e的類型;
若e是一個x值(xvalue),則傳回值為T&&; ?
若e是一個純右值(prvalue),則傳回值為T。

 

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>#include <vector>#include <map>void mytest(){    int i;    decltype(i)j = 0;    std::cout << typeid(j).name() << std::endl; // j ---> int    float a;    double b;    decltype(a+b) c;    std::cout << typeid(c).name() << std::endl; // c ---> double    std::vector<int> vec;    typedef decltype(vec.begin()) vectype;    vectype k;    std::cout << typeid(k).name() << std::endl;    for (k = vec.begin(); k < vec.end(); k++)    {        // do some thing ...    }    enum // 匿名枚舉變數    {        OK, Error, Warning     } flag;    decltype(flag) tmp = OK;    std::cout << typeid(tmp).name() << std::endl;    return;}int main(){    mytest();    system("pause");    return 0;}

 

c++11 decltype

聯繫我們

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