auto return type on a function
How can we deduct the return type of a function? With unknown input type (templated).
First we have to know that
decltype(x + y)
gives us the type of the resulting expression x + y.
Now if we don’t have anything cool from modern C++, how we can implement “auto” return?
template<typename T, typename U>
decltype(x + y) add(T x, U y) {
return x + y;
}
But this doesn’t work, as at the point of decltype our compiler doesn’t know anything about x and y1.
So… what cursed thing we can do? In C++11 we can declare the return parameter as following:
template<typename T, typename U>
auto add(T x, U y) -> decltype(x + y) {
return x + y;
}
Now our compiler knows what is x and y!
And thankfully, since C++14 you can just do the following:
template<typename T, typename U>
auto add(T x, U y) {
return x + y;
}
And the compiler will do the rest for you.
Footnotes:
1
Putting decltype(T + U) is not valid https://godbolt.org/z/z49EvPE5n