0%

C++ Primer学习笔记(四)

decltype

有时我们想将某一个表达式的结果的类型作为变量的类型

1
decltype(f()) sum = x; // sum has whatever type f returns.
1
2
3
4
const int ci = 0, &cj = ci;
decltype(ci) x = 0; // x has type const int
decltype(cj) y = x; // y has type const int& and is bound to x
decltype(cj) z; // error: z is a reference and must be initialized
1
2
3
4
// decltype of an expression can be a reference type
int i = 42, *p = &i, &r = i;
decltype(r + 0) b; // ok: addition yields an int; b is an (uninitialized) int
decltype(*p) c; // error: c is int& and must be initialized

decltype(*p)代表引用类型

  • decltype(()):仅代表引用类型

    1
    2
    int i;
    decltype((i)) d; // error: d is int& and must be initialized

Exercises Section 2.5.3
Exercise 2.36:
In the following code, determine the type of each variable and the value each variable has when the code finishes:

int a = 3, b = 4;

decltype(a) c = a;

decltype((b)) d = a;

++c;

++d;

答:c : int, d int &

Exercise 2.37: Assignment is an example of an expression that yields a reference type. The type is a reference to the type of the left-hand operand. That is, if i is an int, then the type of the expression i = x is int&. Using that knowledge, determine the type and value of each variable in this code:

int a = 3, b = 4;

decltype(a) c = a;

decltype(a = b) d = a;

答:c : int ; d : int &

Exercise 2.38: Describe the differences in type deduction between decltype and auto. Give an example of an expression where auto and decltype will deduce the same type and an example where they will deduce differing types.

答:针对引用类型,如下: a是int类型,b是int &

1
2
3
4
5
int i = 0, &r = i;

auto a = r;

decltype(r) b = i;