auto修饰的变量必须被初始化,编译器需要通过初始化来确定auto所代表的类型,而decltype修饰的变量不需要初始化,用来在编译时推导出一个表达式的类型。decltype推导的结果保留表达式的所有属性(cv(const和volatile限定符的统称)、引用)
auto推导左值表达式时,会带引用,推导右值表达式时,不带引用。
struct Foo
{
int x;
};
const Foo foo = Foo();
decltype(foo.x) a = 0; //a->int
decltype((foo.x)) b = a; //b->const int&
int n = 0;
int m = 0;
decltype(n + m) c = 0; //c->int
decltype(n += m) d = c; //d->int&
decltype经常用在泛型编程中,结合auto,返回值类型后置
template<typename T, typename U>
auto add(T t, U u)->decltype(t + u)
{
return t + u;
}
通过返回类型推导,很容易将foo函数的返回类型用在func函数上
int foo(int& f);
float foo(float& f);
template<typename T>
auto func(T& t)->decltype(foo(t))
{
return foo(t);
}