Reputation: 107
From Wikipedia
What is the use of the keyword auto
in this case (below) if not automatic type deduction?
struct SomeStruct {
auto func_name(int x, int y) -> int;
};
auto SomeStruct::func_name(int x, int y) -> int {return x + y; }
What are some of the situations one needs to explicitly have types?
Upvotes: 0
Views: 620
Reputation: 88155
This is the trailing return type. auto
is simply a placeholder that indicates that the return type comes later.
The reason for this is so that the parameter names can be used in computing the return type:
template<typename L, typename R>
auto add(L l, R r) -> decltype(l+r) { return l+r; }
The alternative is:
template<typename L, typename R>
decltype(std::declval<L>()+std::declval<R>())
add(L l, R r)
{ return l+r; }
It's likely that a future addition to the language will be to allow leaving out the trailing return type and instead using automatic type deduction as is permitted with lambdas.
template<typename L, typename R>
auto add(L l, R r) { return l+r; }
Upvotes: 10