使用場景
注意
2、auto和decltype配合使用可以實現不同返回類型
? ? ?在C++中經常要用到很長的變量名,如果已經有變量和你將使用的變量是一個類型,即可使用decltype關鍵字
來申明一樣的類型變量。
decltype原理? ? ?返回現有變量類型,decltype是一個關鍵字,而不是一個函數,這有啥區別呢?decltype在編譯階段返回變量類
型,而不是在運行階段傳遞不同變量返回不同值。
decltype使用范例
1、復雜已知變量類型
map<string, vector<string>> str_map;
decltype(str_map) str_map_new;
2、表達式返回值類型
int a, b;
decltype(a + b) a;
3、函數返回值
int foo(int i) {return i;
}
double foo(double d) {return d;
}template<typename T>
auto getNum(T t)->decltype(foo(t)) {return foo(t);
}
上面的getNum后面還有一大串,我們后面會驚奇地發現C++14已經去掉了這些,所有代碼看起來非常輕盈,如下:
#include<iostream>
#include<map>
#include<string>
#include<vector>
using namespace std;
int foo(int i) {return i;
}
double foo(double d) {return d;
}template<typename T>
auto getNum(T t) {return foo(t);
}
int main()
{int a =5 ;cout<<getNum(a)<<endl;cout << getNum(1.2) << endl;}
注意
1、decltype兩個括號返回變量引用類型
int i;
decltype((i)) r = i;
decltype(i) a;
2、auto和decltype配合使用可以實現不同返回類型