據我所知,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 /)。 –