- decltype简介
编译时期推导变量类型和表达式类型,主要应用于模板编程时的类型推导 - decltype规则
对于变量即左值:左值是什么类型就是什么类型,如果有顶层const不忽略,decltype区别于auto,auto需要接受初始化变量deduce type,且如果有顶层const则忽略.
对于表达式:根据表达式返回的值类型确定
C++Primer:The way decltype handles top-level const and references differs subtly from the way auto does. When the expression to which we apply decltype is a variable, decltype returns the type of that variable, including top-level const and references:
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
C++Primer:When we apply decltype to an expression that is not a variable, we get the type that that expression yields. As we’ll see in § 4.1.1 (p. 135), some expressions will cause decltype to yield a reference type. Generally speaking, decltype returns a reference type for expressions that yield objects that can stand on the left-hand side of the assignment:
// 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的变量被双括号包裹的话,例如decltype((value)),总是返回value_type&. -
困惑点
int a=0; decltype(a=1) x=other_value; //基础类型的operator=一般返回type&,类似我们总写operator=时总是返回const class_type&一样(符合基础类型行为)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。