The following C++ code does not compile:
template <typename T>
void f(int, bool = true);
void g()
{
auto h = f<int>;
h(1); // error: too few arguments to function
}
Instead, I have to call h
with the 2nd parameter:
h(1, true);
Why doesn't h(1)
work?
Is there a simple way to alias a template function to bind the template argument while keeping the default function argument?
h
is declared as function pointer, unfortunately it can't specify default arguments.
Default arguments are only allowed in the parameter lists of function declarations
and lambda-expressions, (since C++11)
and are not allowed in the declarations of pointers to functions, references to functions, or in typedef declarations.
You can use a lambda wrapping f
instead. E.g.
auto h = [](int i) { f<int>(i); };
h(1); // -> f<int>(1, true), using f's default argument
Or specify default argument on the lambda too.
auto h = [](int i, bool b = true) { f<int>(i, b); };
h(1); // -> f<int>(1, true), using h, i.e. lambda's default argument
h(1, true); // -> f<int>(1, true), not using default argument
h(1, false); // -> f<int>(1, false), not using default argument