Why is decltype used in trailing return types?

consider the following codes:

template< class T1 , class T2> auto calc( T1 a , T2 b ) { return a + b ; } template< class T1 , class T2> auto calc( T1 a , T2 b ) -> decltype( a + b ) { return a + b ; } 

What is the difference in the second code? Can you give an example where it matters or does it matter here?

+6
source share
1 answer

Note that the usual return type auto is something that is only available for C ++ 14, while the return type with decltype is for C ++ 11. The difference occurs when links enter an image, for example. in code:

 #include <type_traits> struct Test { int& data; auto calc1() { return data; } auto calc2() -> decltype(data) { return data; } }; int main() { int x; Test t{x}; static_assert(std::is_same<int, decltype(t.calc1())>::value, ""); static_assert(std::is_same<int&, decltype(t.calc2())>::value, ""); } 

If you want to remove ->decltype() and save your code in the same way, you can use the C ++ 14 decltype(auto) construct

 decltype(auto) calc3() // same as calc2() above { return data; } 

which also preserves the return type.

If you already know that your return type is a link, just make it explicit

 auto& calc4() // same as calc2() above { return data; } 
+6
source

All Articles