I know that the use of auto
keyword can automatically deduce the type of the variable from the Rvalue. Then why does the following function snippet in my code have a compilation error?
auto getName(auto str = "John Doe") {
return str;
}
The compilation error is 'auto' not allowed in function prototype. I googled a bit and I think auto
can not be used in the function prototypes. Why So?
You can use auto
in a lambda expression, but not a normal function.
To get the same effect, you can define a function template instead:
template <class T>
T getname(T input = "John Doe") {
return input;
}
But be aware that this default value for the argument will only work for types that can actually be initialized from a string literal.
Oh, and as an aside, names starting with str
are reserved, so it would be better to use a different name.