0x00 前言
文章中的文字可能存在语法错误以及标点错误,请谅解;
如果在文章中发现代码错误或其它问题请告知,感谢!
0x01 decltype简介
decltype
是“declare type”的缩写,翻译为“声明类型”。decltype
为C++11关键字和auto
功能一样,可以在编译时自动进行类型推导。
decltype
类型推导不像auto
可以从变量声明初始化表达式获得变量类型,而是通过一个普通表达式作为参数,返回该表达式类型(注意,decltype不对表达式进行求值)。
0x02 decltype用法
decltype
一般使用格式如下:
decltype(exp) varname;
exp
为普通表达式,可以是任何复杂形式但不能为void类型,否则编译报错。
C++decltype举例:
int i = 4;
decltype(i) a;//推导结果为int即a的类型为int
decltype(1.2) b = 5.5; //推导结果为double即b的类型为double
decltype(1.2) c = 5; //推导结果为double即c的类型为double,和=右边的值无关
decltype(i + 100)d; /推导结果为double即d的类型为double,d没有被初始化
0X03 decltype推导规则
若exp
是一个没有带括号的普通表达式则那么decltype(exp
)类型和exp
的类型一样;
若exp
是一个带括号()的表达式或exp
为左值( 左值是指那些在表达式执行结束后依然存在的数据)则decltype(exp)
类型就是exp
的引用(假设exp
类型为T
,则decltype(exp)
类型就是T&
);
若exp
是函数调用则decltype(exp)
类型和函数返回值一样。
例:
#include <string>
using namespace std;
class Student{
public:
static int TotalNum;
string StudentName;
int Age;
float Scores;
};
int Student::TotalNum = 0;
class Test{
public:
int x;
};
int&& Func1(void); //返回值为int&&
int& Func2(int, char); //返回值为int&
int Func3(double); //返回值为 int
const int& Func4(int, int); //返回值为 const int&
const int&& Func5(void); //返回值为 const int&&
int main(){
int N = 0;
int M = 0;
const int &J = N;
Student stu;
Test test;
decltype(N) a = N; //N 为 int 类型,a 被推导为 int 类型
decltype(J) b = N; //J 为 const int& 类型, b 被推导为 const int& 类型
decltype(Student::Age) c = N; //Age为类 Student 的一个 int 类型的成员变量,c 被推导为 int 类型
decltype(Student::TotalNum) d = N; //TotalNum 为类 Student 的一个 int 类型的成员变量,d 被推导为 int 类型
decltype(stu.StudentName) name = "Wang Qingchuan"; //StudentName 为类 Student 的一个 string 类型的成员变量,name 被推导为 string 类型
decltype(Func1()) e = 0; //e 的类型为 int&&
decltype(Func2(1, 'A')) f = N; //f 的类型为 int&
decltype(Func3(1.2)) g = N; //g 的类型为 int
decltype(Func4(1,2)) h = N; //h 的类型为 const int &
decltype(Func5()) i = 0; // i 的类型为 const int&&
//带有括号的表达式
decltype(test.x) j = N; //test.x为类的成员访问表达式,j的类型为 int
decltype((test.x)) k = N; //test.x带有括号,k 的类型为 int&。
//加法表达式
decltype(N+M) l = N; //n+m 得到一个右值,符合推导规则一,所以推导结果为 int
decltype(N = N+M) m = N; //n=n+m 得到一个左值,符号推导规则三,所以推导结果为 int&
return 0;
}
以上。
参考文档:
1.http://c.biancheng.net/view/7151.html#:~:text=decltype%20%E6%98%AF%E2%80%9Cdeclare%20type%E2%80%9D%E7%9A%84%E7%BC%A9%E5%86%99%EF%BC%8C%E8%AF%91%E4%B8%BA%E2%80%9C%E5%A3%B0%E6%98%8E%E7%B1%BB%E5%9E%8B%E2%80%9D%E3%80%82.%20%E6%97%A2%E7%84%B6%E5%B7%B2%E7%BB%8F%E6%9C%89%E4%BA%86%20auto%20%E5%85%B3%E9%94%AE%E5%AD%97%EF%BC%8C%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E9%9C%80%E8%A6%81%20decltype%20%E5%85%B3%E9%94%AE%E5%AD%97%E5%91%A2%EF%BC%9F.,%28exp%29%20varname%20%3D%20value%3B%20%E5%85%B6%E4%B8%AD%EF%BC%8Cvarname%20%E8%A1%A8%E7%A4%BA%E5%8F%98%E9%87%8F%E5%90%8D%EF%BC%8Cvalue%20%E8%A1%A8%E7%A4%BA%E8%B5%8B%E7%BB%99%E5%8F%98%E9%87%8F%E7%9A%84%E5%80%BC%EF%BC%8Cexp%20%E8%A1%A8%E7%A4%BA%E4%B8%80%E4%B8%AA%E8%A1%A8%E8%BE%BE%E5%BC%8F%E3%80%82.
2.https://www.cnblogs.com/QG-whz/p/4952980.html