据我所知,decltype
和auto
将试图找出什么类型的东西是。decltype vs auto
如果我们定义:
int foo() {
return 34;
}
然后,两个声明是合法的:
auto x = foo();
cout << x << endl;
decltype(foo()) y = 13;
cout << y << endl;
你能告诉我decltype
和auto
之间的主要区别是什么?
据我所知,decltype
和auto
将试图找出什么类型的东西是。decltype vs auto
如果我们定义:
int foo() {
return 34;
}
然后,两个声明是合法的:
auto x = foo();
cout << x << endl;
decltype(foo()) y = 13;
cout << y << endl;
你能告诉我decltype
和auto
之间的主要区别是什么?
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
是可能的地方大卫·罗德里格斯的答案。
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
不能用来定义返回类型。
一般来说,如果你需要知道你所要初始化变量的类型,使用汽车。 decltype更适用于需要非变量类型的东西,如返回类型。
@JesseGood在问这个问题之前,我读了这个帖子,并且正在寻找一个更清晰的解释 –
类似问题: [1]:http://stackoverflow.com/questions/11459928/equivalence-between-decltype-and-汽车 [2]:http://stackoverflow.com/questions/6869888/the-relationship-between-auto-and-decltype – crnlx
@JamesLeonard:好吧,我不知道更好的解释[比斯科特迈耶斯(HTTP:// CPP-未来。COM /存档/ 2011/04 /出现和消失的-consts式-C /)。 –