在某些情况下,不需要或者不能定义变量,但是希望得到某种类型,这时候就可以用C++11提供的decltype关键字了,它的作用是在编译器编译的时候推导出一个表达式的类型。
语法:
复制代码
1
2decltype (表达式)
decltype是"declare type “的缩写,意思是"声明类型”,decltype的推导是在编译期完成的,它只是用于表达式类型的推导,并不会计算表达式的值。
代码如下:
复制代码
1
2
3
4
5int a = 10; decltype(a) b = 99;// b -> int decltype(a + 3.14) c = 52.13;// c -> double decltype(a + b * c) d = 520.1314;//d -> double
推导规则:
1.表达式为普通变量或者普通表达式或者类表达式,在这种情况下,使用decltype推导出的类型和表达式的类型是一致的。
代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26#include <iostream> using namespace std; class Test { public: int num = 9; string text; static const int value = 110; }; int main() { int x = 99; const int &y = x; decltype(x) a = x;// a -> int decltype(y) b = x;// b ->const int& decltype(Test::value) c = 0; // c -> const int Test t; decltype(t.text) d = "hello world";//d -> string }
2.表达式是函数调用,使用decltype推导出的类型和函数返回值一致。
注意:
函数func_cint()返回的是一个纯右值,对于纯右值而言,只有类类型可以携带const,volatile限定符,除此之外需要忽略掉这两个限定符,因此推导出的变量d的类型为int而不是const int。
代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32#include <iostream> using namespace std; class Test { }; int func_int (){} int &func_int_r(){} int &&func_int_rr(){} const int func_cint(){} const int& func_cint_r(){} const int && func_cint_rr(){} const Test func_ctest(){} int main() { int n = 100; decltype(func_int()) a = 0;// a ->int decltype(func_int_r()) b = n;//b ->int & decltype(func_int_rr()) c = 0;//c ->int && decltype (func_cint()) d = 0;/*d ->int 对于纯右值而言, 只有类类型可以携带const,volatile限定符, 除此之外需要忽略掉这两个限定符, 因此推导出的变量d的类型为int而不是const int。*/ decltype(func_cint_r()) e = n;//e -> const int & decltype ( func_cint_rr()) f = 0;//f ->const int && decltype(func_ctest()) g = Test();// g -> const Test }
3.表达式是一个左值,或者被括号()包围,使用decltype推导出的是表达式类型的引用(如果有const,volatile限定符不能忽略)。
代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23#include <iostream> using namespace std; class Test { public: int num = 9; string text; static const int value = 110; }; int main() { const Test obj; decltype (obj.num) a = 3;//a -> int decltype ((obj.num)) b = a;// b ->const int & int n = 0, m = 0; decltype(n + m) c = 0;// c -> int decltype(n = n+m) d = n// d -> int & n = n+m,最后得到的n是一个左值 }
最后
以上就是温婉银耳汤最近收集整理的关于[C++11]decltype类型推导规则的全部内容,更多相关[C++11]decltype类型推导规则内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复