decltype vs auto

Jam*_*ard 43 c++ type-inference

据我了解,双方decltypeauto会尝试找出的东西是什么类型.

如果我们定义:

int foo () {
    return 34;
}
Run Code Online (Sandbox Code Playgroud)

然后这两个声明都是合法的:

auto x = foo();
cout << x << endl;

decltype(foo()) y = 13;
cout << y << endl;
Run Code Online (Sandbox Code Playgroud)

你能否告诉我decltype和之间的主要区别auto是什么?

Man*_*rse 43

decltype给出传递给它的表达式的声明类型.auto与模板类型推导相同.因此,例如,如果您有一个返回引用的函数,auto仍然是一个值(您需要auto&获取引用),但decltype它将是返回值的类型.

#include <iostream>
int global{};
int& foo()
{
   return global;
}

int main()
{
    decltype(foo()) a = foo(); //a is an `int&`
    auto b = foo(); //b is an `int`
    b = 2;

    std::cout << "a: " << a << '\n'; //prints "a: 0"
    std::cout << "b: " << b << '\n'; //prints "b: 2"

    std::cout << "---\n";
    decltype(foo()) c = foo(); //c is an `int&`
    c = 10;

    std::cout << "a: " << a << '\n'; //prints "a: 10"
    std::cout << "b: " << b << '\n'; //prints "b: 2"
    std::cout << "c: " << c << '\n'; //prints "c: 10"
 }
Run Code Online (Sandbox Code Playgroud)

另请参阅DavidRodríguez关于其中只有一个autodecltype可能的地方的答案.


Dav*_*eas 35

auto(在推断类型的上下文中)仅限于定义具有初始化器的变量的类型.decltype是一个更广泛的结构,以额外信息为代价,将推断表达式的类型.

auto可以使用的情况下,它更简洁decltype,因为您不需要提供将从中推断出类型的表达式.

auto x = foo();                           // more concise than `decltype(foo()) x`
std::vector<decltype(foo())> v{ foo() };  // cannot use `auto`
Run Code Online (Sandbox Code Playgroud)

auto当为函数使用尾随返回类型时,关键字也用在完全不相关的上下文中:

auto foo() -> int;
Run Code Online (Sandbox Code Playgroud)

这里auto仅仅是一个领导者,这样编译器知道,这是一个尾随返回类型的声明.虽然上面的例子可以简单地转换为旧样式,但在通用编程中它很有用:

template <typename T, typename U>
auto sum( T t, U u ) -> decltype(t+u)
Run Code Online (Sandbox Code Playgroud)

请注意,在这种情况下,auto不能用于定义返回类型.