#include<string>usingnamespace std;classStudent{public:staticint total;
string name;int age;float scores;};int Student::total =0;intmain(){int n =0;constint&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 类型return0;}
//函数声明int&func_int_r(int,char);//返回值为 int&int&&func_int_rr(void);//返回值为 int&&intfunc_int(double);//返回值为 intconstint&fun_cint_r(int,int,int);//返回值为 const int&constint&&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 的类型为 intdecltype(fun_cint_r(1,2,3)) x = n;//x 的类型为 const int &decltype(func_cint_rr()) y =0;// y 的类型为 const int&&
usingnamespace std;classBase{public:int x;};intmain(){const Base obj;//带有括号的表达式decltype(obj.x) a =0;//obj.x 为类的成员访问表达式,符合推导规则一,a 的类型为 intdecltype((obj.x)) b = a;//obj.x 带有括号,符合推导规则三,b 的类型为 int&。//加法表达式int n =0, m =0;decltype(n + m) c =0;//n+m 得到一个右值,符合推导规则一,所以推导结果为 intdecltype(n = n + m) d = c;//n=n+m 得到一个左值,符号推导规则三,所以推导结果为 int&return0;}
关于decltype推导函数
#include<iostream>usingnamespace std;voidfoo(){printf("foo\n");}voidfoo2(){printf("foo2\n");}boolfoo3(){printf("foo3\n");returntrue;}intmain(){decltype(&foo) a = foo2;decltype(&foo) b = foo3;//invalid conversion from 'bool (*)()' to 'void (*)()a();//foo2return0;}