The most obvious answer could be - because the standard says so.
That's fine, but I'm wrapping my head around it to understand the reasons behind this choice.
Consider the following example:
template<typename T>
struct S { S(T) {} };
S f() { return 0; }
int main() {
auto s = f();
(void)s;
}
It fails to compile with errors like:
error: use of class template 'S' requires template arguments; argument deduction not allowed in function return type
Quite easy to fix, it isn't a problem, something like this works just fine:
auto f() { return S{0}; }
However, I'd like to understand what were the drawbacks of allowing class template arguments deduction also in function return types.
At a first glance, it looks just like a silly limitation, but I'm pretty sure I'm missing something important here.
So the only real difference between auto and template type deduction is that auto assumes that a braced initializer represents a std::initializer_list , but template type deduction doesn't.
Template argument deduction is used when selecting user-defined conversion function template arguments. A is the type that is required as the result of the conversion. P is the return type of the conversion function template.
A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.
There's nothing language-lawery here: If you specify a return type (and not auto
or T
where T
is a template type), that return type has to be valid. let me give you even a simpler, better example:
std::vector function() {
return std::vector<int>();
}
Obviously it fails to compile, even without fancy templates, auto
and type deductions, because std::vector
isn't a type, std::vector<int>
is.
When you specify S
as a return type you basically
S
isn't a type, S<int>
is.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With