看看以下程式有什麼不一樣
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <iostream> using namespace std; struct Obj { Obj() { cout << "Default Constructor\n"; } ~Obj() { cout << "Destructor\n"; } Obj(const Obj &) { cout << "Copy Constructor\n"; } Obj(Obj &&) { cout << "Move Constructor\n"; } }; template <typename T> auto outer(T && obj) { return std::forward<T>(obj); }
int main() { auto& obj = outer(Obj()); return 0; }
|
和
1 2 3 4
| template <typename T> decltype(auto) outer(T && obj) { return std::forward<T>(obj); }
|
差異就在於auto和decltype的用途不太一樣,auto會去掉reference,而decltype(auto)不會
C++11’s solution
C++11也可以達到decltype(auto)的方式,不過寫法比較繁瑣
1 2 3 4
| template <typename T> auto outer(T&& obj) -> decltype(std::forward<T>(obj)) { return std::forward<T>(obj); }
|