2012-08-23 71 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更適用於需要非變量類型的東西,如返回類型。

相關問題