2012-08-23 49 views
29

据我所知,decltypeauto将试图找出什么类型的东西是。decltype vs auto

如果我们定义:

int foo() { 
    return 34; 
} 

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

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

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

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

+1

@JesseGood在问这个问题之前,我读了这个帖子,并且正在寻找一个更清晰的解释 –

+1

类似问题: [1]:http://stackoverflow.com/questions/11459928/equivalence-between-decltype-and-汽车 [2]:http://stackoverflow.com/questions/6869888/the-relationship-between-auto-and-decltype – crnlx

+1

@JamesLeonard:好吧,我不知道更好的解释[比斯科特迈耶斯(HTTP:// CPP-未来。COM /存档/ 2011/04 /出现和消失的-consts式-C /)。 –

回答

25

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

也看到其中只有auto一个或decltype是可能的地方大卫·罗德里格斯的答案。

29

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不能用来定义返回类型。

0

一般来说,如果你需要知道你所要初始化变量的类型,使用汽车decltype更适用于需要非变量类型的东西,如返回类型。

相关问题