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);
}
本文深入探讨了C++中auto与decltype的使用区别。auto关键字用于变量声明时,变量必须初始化以确定其类型;而decltype可根据表达式推导类型,即使未初始化。此外,文章详细解析了两者在推导左值与右值表达式时的行为差异,并通过实例展示了它们在模板编程中的应用。

448

被折叠的 条评论
为什么被折叠?



