Default argument for abbreviated function template

Viewed 86

I noticed that it looks like I can not use default argument as I expect for an abbreviated function template.

#include <iostream>

auto f(const auto x = 0) {
    return x + sizeof(x);
}

int main() { 
    std::cout << f() << std::endl; // << broken
    std::cout << f(0) << std::endl;
    std::cout << f(short(8470)) << std::endl;
}

What is the reason for this?

My guess is that template machinery never looks at default argument so we get this nonsensical situation where I can define a templated function that looks like it defaults to T=int (where T is hidden template type), but there seems to be no way to call it without manually specifying type: (f<int>()).

This is mostly language trivia, I do not consider this a real problem, but it does look weird™ that function template does not have int as default template type.

1 Answers

You have the same problem with template:

template<class T>
auto f(const T x = 0) {
    return x + sizeof(x);
}

My guess is that the transformation done for auto parameter is essentially the above code.

To make it work, you have to specify default template type of T:

template<class T = int>
auto f(const T x = 0) {
    return x + sizeof(x);
}

While abbreviated templates are useful, you have to use template when you need more control. This would also be the case if you have a function with multiple arguments that have to be the same type for example.

Related