Re: auto for function return type is kind of useless, is it?
On Jan 17, 10:53 pm, Peter wrote:
What is the use of the auto keyword for function return types,
if I anway have to declare the type by hand after the function header?
One advantage is "scope". If you declare the return type at the end
the compiler already knows the parameters including whether the
function is a member function of not.
One of the first examples to demonstrate the benifit was
template<class T, class U>
decltype(a+b) // FAILS, a and b are not yet known
add(T a, U b);
template<class T, class U>
decltype(declval<T>()+declval<U>()) // works, but is tedious
add (T a, U b);
template<class T, class U>
auto add(T a, U b)
-> decltype(a+b); // fine, compiler knows what a and b are
But it also works with member typedefs, for example:
class myuserdefinedtype
{
public:
typedef int something;
auto bar() -> something;
};
auto myuserdefinedtype::bar() -> something
{
...
}
instead of
myuserdefinedtype::something myuserdefinedtype::bar()
{
...
}
Unfortunately, the compiler allows omitting the return type entirely
only for lambdas with a single return statement. I whish I could do
the same for named functions. But it is possible to reduce redundancy
using a macro:
#define AUTO_RETURN(...) \
-> typename std::decay<decltype(__VA_ARGS__)>::type \
{ return __VA_ARGS__; }
template<class T, class U, class V>
auto baz( T a, U b, V c )
AUTO_RETURN( a*(b+c) )
For more complicated functions (more than just a single return
statement) I think it's okay to let the user specify the return type
manually.