decltype vs auto

时间:2012-08-23 02:41:25

标签: c++ type-inference

据我了解,decltypeauto都会尝试弄清楚某事物的类型。

如果我们定义:

int foo () {
    return 34;
}

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

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

decltype(foo()) y = 13;
cout << y << endl;

您能否告诉我decltypeauto之间的主要区别是什么?

4 个答案:

答案 0 :(得分:38)

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"
 }

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

答案 1 :(得分:33)

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

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

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

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

auto foo() -> int;

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

template <typename T, typename U>
auto sum( T t, U u ) -> decltype(t+u)

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

答案 2 :(得分:1)

修改@Mankarse的示例代码,我认为是个更好的选择:

#include <iostream>
int global = 0;
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 << "global: " << global << '\n'; //prints "global: 0"

    std::cout << "---\n";

    //a is an `int&`
    a = 10;

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

    return 0;

}

答案 3 :(得分:0)

通常,如果您需要初始化变量的类型,请使用 auto 。当您需要非变量的类型(如返回类型)时,最好使用 decltype