2015-09-07 74 views
2

我在閱讀Scott Meyers的Effective Modern C++我試圖在我的機器上爲推導類型章節提供的示例。追尾返回類型和右值

他提供了這樣的功能:

template <typename Container, typename Index> 
auto decltype_test_1(Container& c, Index i) -> decltype(c[i]) 
{ 
    return c[i]; 
} 

然後它使用函數以這種方式:

std::deque<int> d; 
… 
decltype_test_1(d, 5) = 10; // authenticate user, return d[5], 
          // then assign 10 to it; 
          // this won't compile! 

說,它不會編譯。我嘗試使用MSVC,它編譯。我寫在main如下:

std::deque<int> d; 
d.push_back(0); 
d.push_back(1); 
d.push_back(2); 

decltype_test_1(d, 0) = 10; 

for each (auto item in d) 
    cout << item << endl; 

我不明白爲什麼它編譯和,最重要的是,它顯示10爲雙端隊列的第一個元素。對於他解釋的這段代碼是錯誤的。它爲什麼在這裏工作?我錯過了什麼?

+1

它看起來像有使用'decltype',他說,它工作正常,其次是一個例子,而不'decltype'他說,這是不完全正確的例子。函數調用是後者的一部分。當然,還有第三種是「decltype(auto)」。 – chris

+0

你的第二個片段調用函數'authAndAccess',而第一個片段定義'decltype_test_1'。我沒有這本書,因此我不知道它是否是一個錯字... – user463035818

回答

6

這番話是不是與後decltype的C++ 11例,它是關於C++ 14版本auto類型推演:

template <typename Container, typename Index> 
auto decltype_test_1(Container& c, Index i) //no trailing return 
{ 
    return c[i]; 
} 

使用這個版本中,例如將無法編譯,因爲類型將被推導爲一個值而不是一個引用,所以不能直接分配給該函數調用的結果。

如本書的下一頁所示,獲得正確類型而沒有尾隨返回類型的方法是使用decltype(auto)而不是auto

template <typename Container, typename Index> 
decltype(auto) decltype_test_1(Container& c, Index i) 
{ 
    return c[i]; 
} 
+0

所以在C++ 11的情況下,'decltype(c [i])'將返回對'c [i]'的引用' , 我對嗎? – Astinog

+1

@Agostino確實,看看[這個例子]的編譯器錯誤(http://coliru.stacked-crooked.com/a/4e55a5cbdf7f46b7),看看有什麼不同。 – TartanLlama

+0

非常感謝。只是一件事,與這個問題沒有關係,但我想知道'template struct tt;'的意思,我可以在哪裏讀到它?你能提供一個鏈接嗎?再次感謝 – Astinog