Omit return type in C++0x
- by Clinton
I've recently found myself using the following macro with gcc 4.5 in C++0x mode:
#define RETURN(x) -> decltype(x) { return x; }
And writing functions like this:
template <class T>
auto f(T&& x) RETURN (( g(h(std::forward<T>(x))) ))
I've been doing this to avoid the inconvenience having to effectively write the function body twice, and having keep changes in the body and the return type in sync (which in my opinion is a disaster waiting to happen).
The problem is that this technique only works on one line functions. So when I have something like this (convoluted example):
template <class T>
auto f(T&& x) -> ...
{
auto y1 = f(x);
auto y2 = h(y1, g1(x));
auto y3 = h(y1, g2(x));
if (y1) { ++y3; }
return h2(y2, y3);
}
Then I have to put something horrible in the return type.
Furthermore, whenever I update the function, I'll need to change the return type, and if I don't change it correctly, I'll get a compile error if I'm lucky, or a runtime bug in the worse case. Having to copy and paste changes to two locations and keep them in sync I feel is not good practice.
And I can't think of a situation where I'd want an implicit cast on return instead of an explicit cast.
Surely there is a way to ask the compiler to deduce this information. What is the point of the compiler keeping it a secret? I thought C++0x was designed so such duplication would not be required.