I am trying to use a function with a default argument as a function pointer template parameter:
template <void (*F)()>
class A {};
void foo1(int a = 0) {}
void foo2() {}
int main()
{
//A<foo1> a1; <-- doesn't work
A<foo2> a2;
}
The compiler error is:
main.cpp:7:7: error: could not convert template argument ‘foo1’ to ‘void (*)()’
Is there specific syntax for this to work? Or a specific language limitation? Otherwise, the alternative is to have two separate functions instead of a default parameter:
void foo1(int a) {}
void foo1() { foo1(0); }
Update
I understand that the signatures are different, but I’m wondering if there is a way to make this work conveniently without needing to modify all the functions with default parameters?
According to section 8.3.6 of the C++ standard,
Since
A<foo1>is not a call of the function, default arguments are ignored. In fact, they are ignored in all contexts except the calls of the function, for examplewill not compile, and produce the same message that you get when trying to use
foo1as a template parameter:This makes sense, because evaluating default arguments is a separate step in the invocation:
The presence of default arguments does not alter the signature of your function. For example, you cannot use a single-argument function with a default argument to override a no-argument virtual member function.