1. 程式人生 > >【C++】C++中typedef、auto與decltype的作用

【C++】C++中typedef、auto與decltype的作用

typedef

類型別名(type alias)是一個名字,使用typedef不會真正地建立一種新的資料型別,它只是已經存在資料型別的一個新名稱。
語法:

typedef type name;

其中type是c++中的資料型別,name是這個型別的一個別名。

C++11提供了引用的功能,關於引用的詳細介紹可以參考筆者之前的文章。引用為變數提供別名,typedef則是為型別提供別名。

例如:

#include <iostream>
int main(){
    int m = 10;//使用int定義變數m
    typedef int integer;//建立一個int的別名為integer
integer n = 20;//使用integer定義變數n typedef integer integer_type;//建立一個integer的別名為integer_type integer_type o = 30;//使用integer_type定義變數o std::cout << "m + n + o = " << (m+n+o) << std::endl;//運算 return 0; }

輸出結果:

m + n + o = 60

上面有兩個別名integer和integer_type,integer_type有integer建立而來,integer_type和integer都是屬於int型別。

auto

auto是c++11標準定義的一個型別推斷的關鍵字,auto能夠讓編譯器自動去分析表示式所屬的型別,與特定的資料型別不同(比如double),讓編譯器通過初始值來推算變數的型別。顯然auto定義必須有初始值。
比如:

#include <iostream>
#include <typeinfo>
#include <set>
using namespace std;

int main()
{
auto x = 4;
auto y = 3.37;
auto ptr = &x;
cout << "x type is : 
" << typeid(x).name() << endl << "y type is : " << typeid(y).name() << endl << "ptr type is : " << typeid(ptr).name() << endl; cout << "--------------------------" << endl; set<string> strs; strs.insert({"green","blue","red"}); for(auto it = strs.begin();it != str.end();it++){//遍歷容器中的元素 cout << *it << " "; } cout << "--------------------------" << endl; //r是一個int引用型別 auto &r = x; cout << "r type is : " << typeid(r).name() << endl; return 0; }

輸出結果:

x type is : i
y type is : d
ptr type is : Pi
--------------------------
blue green red
--------------------------
r type is : i

上面的i表示int,d表示double,Pi表示int*(int型別的指標)。

decltype

decltype也是c++11提供的一個關鍵字,它可以從變數或表示式中提取型別。

int f() { return 10; }
int main(){
    decltype(f()) val;//f()返回值是int型別,val是int型別

    const int &v = 10;
    decltype(v) rval;//錯誤,rval 是引用型別,必須要初始化

    int pv = 10;
    int *p = &pv;
    decltype(p) pp;//正確,pp是int*型別。
    decltype(*p) c;//錯誤,c是int&型別(int引用型別),必須要初始化
    return 0;
}

如果表示式是解引用操作(*),那麼decltype將會得到引用型別。如上面的decltype(*p)。

如果decltype裡面有兩個括號,那麼是一個引用型別

decltype((i)) d;//錯誤,d是int&,必須要初始化。
decltype(i) e;//正確,e是一個(未初始化)int。

 

注意:

decltype((variable))(注意是雙括號)的結果永遠是引用,而decltype(variable)結果只有當variable本身是引用時才是引用。