decltype 是“declare type”的缩写,译为“声明类型”。
既然已经有了 auto 关键字,为什么还需要 decltype 关键字呢?因为 auto 并不适用于所有的自动类型推导场景,在某些特殊情况下 auto 用起来非常不方便,甚至压根无法使用,所以 decltype 关键字也被引入到 C++11 中。auto varname = value;
decltype(exp) varname = value;
=
右边的初始值 value 推导出变量的类型,而 decltype 根据 exp 表达式推导出变量的类型,跟=
右边的 value 没有关系。decltype(exp) varname;
- int a = 0;
- decltype(a) b = 1; //b 被推导成了 int
- decltype(10.8) x = 5.5; //x 被推导成了 double
- decltype(x + 100) y; //y 被推导成了 double
( )
包围的表达式,或者是一个类成员访问表达式,或者是一个单独的变量,那么 decltype(exp) 的类型就和 exp 一致,这是最普遍最常见的情况。( )
包围,那么 decltype(exp) 的类型就是 exp 的引用;假设 exp 的类型为 T,那么 decltype(exp) 的类型就是 T&。
- #include <string>
- using namespace std;
- class Student{
- public:
- static int total;
- string name;
- int age;
- float scores;
- };
- int Student::total = 0;
- int main(){
- int n = 0;
- const int &r = n;
- Student stu;
- decltype(n) a = n; //n 为 int 类型,a 被推导为 int 类型
- decltype(r) b = n; //r 为 const int& 类型, b 被推导为 const int& 类型
- decltype(Student::total) c = 0; //total 为类 Student 的一个 int 类型的成员变量,c 被推导为 int 类型
- decltype(stu.name) url = "http://c.biancheng.net/cplus/"; //total 为类 Student 的一个 string 类型的成员变量, url 被推导为 string 类型
- return 0;
- }
- //函数声明
- int& func_int_r(int, char); //返回值为 int&
- int&& func_int_rr(void); //返回值为 int&&
- int func_int(double); //返回值为 int
- const int& fun_cint_r(int, int, int); //返回值为 const int&
- const int&& func_cint_rr(void); //返回值为 const int&&
- //decltype类型推导
- int n = 100;
- decltype(func_int_r(100, 'A')) a = n; //a 的类型为 int&
- decltype(func_int_rr()) b = 0; //b 的类型为 int&&
- decltype(func_int(10.5)) c = 0; //c 的类型为 int
- decltype(fun_cint_r(1,2,3)) x = n; //x 的类型为 const int &
- decltype(func_cint_rr()) y = 0; // y 的类型为 const int&&
( )
包围:
- using namespace std;
- class Base{
- public:
- int x;
- };
- int main(){
- const Base obj;
- //带有括号的表达式
- decltype(obj.x) a = 0; //obj.x 为类的成员访问表达式,符合推导规则一,a 的类型为 int
- decltype((obj.x)) b = a; //obj.x 带有括号,符合推导规则三,b 的类型为 int&。
- //加法表达式
- int n = 0, m = 0;
- decltype(n + m) c = 0; //n+m 得到一个右值,符合推导规则一,所以推导结果为 int
- decltype(n = n + m) d = c; //n=n+m 得到一个左值,符号推导规则三,所以推导结果为 int&
- return 0;
- }
- #include <vector>
- using namespace std;
- template <typename T>
- class Base {
- public:
- void func(T& container) {
- m_it = container.begin();
- }
- private:
- typename T::iterator m_it; //注意这里
- };
- int main()
- {
- const vector<int> v;
- Base<const vector<int>> obj;
- obj.func(v);
- return 0;
- }
T::iterator
并不能包括所有的迭代器类型,当 T 是一个 const 容器时,应当使用 const_iterator。
- template <typename T>
- class Base {
- public:
- void func(T& container) {
- m_it = container.begin();
- }
- private:
- decltype(T().begin()) m_it; //注意这里
- };
T().begin()
这种写法,以上代码我在 VS2019 下测试通过,在 VS2015 下测试失败。联系客服