3

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.

NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • 1
    Possible dupe: [auto type deduction for argument with default value](https://stackoverflow.com/questions/43643473/) – Remy Lebeau Aug 19 '21 at 23:38
  • @RemyLebeau nice find, but I think that was a old gcc extension... auto arguments for normal fns are C++20 I believe – NoSenseEtAl Aug 19 '21 at 23:41
  • it may have originated as a gcc extension in C++14, but I think some of the answers in that link still apply in this situation under the standardized flavor in C++20 – Remy Lebeau Aug 19 '21 at 23:46

1 Answers1

4

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.

Phil1970
  • 2,605
  • 2
  • 14
  • 15