I have a function which accepts an operator object as an argument. This operator is treated sort of like a callback. The type of this operator object is a template parameter. How can I specify a default parameter for it?
#include <iostream>
template<class IT, class NT>
class A
{
public:
class DefaultHandler
{
public:
NT foo() { return NT(); }
};
template <class HANDLER>
void action(HANDLER h = DefaultHandler()) // This default parameter is accepted by the compiler but appears to have no effect
{
std::cout << h.foo() << std::endl;
}
};
int main()
{
A<int, double> a;
// I want this to be legal:
a.action(); // error: no matching function for call to ‘A<int, double>::action()’
//a.action(A<int, double>::DefaultHandler()); // Works
return 0;
}
Having said that default arguments for template are not allowed in current standard. Following is a simple work around to solve your problem:
template <class HANDLER>
void action(HANDLER h) {
std::cout << h.foo() << std::endl;
}
void action() { // wrapper
action(DefaultHandler()); // call the desired funciton
}
Provide a wrapper which makes the effect of default parameter for action(). Demo.
Default parameters for template functions are not allowed in C++03 but are allowed in C++11.
References:
C++03 Standard: 14.1.9:
A default template-argument is a template-argument (14.3) specified after = in a template-parameter. Adefault template-argument may be specified for any kind of template-parameter (type, non-type, template).A default template-argument may be specified in a class template declaration or a class template definition. A default template-argument shall not be specified in a function template declaration or a function template definition, nor in the template-parameter-list of the definition of a member of a class template. A default template-argument shall not be specified in a friend template declaration.
C++11: 14.1.9:
A default template-argument is a template-argument (14.3) specified after = in a template-parameter. A de-fault template-argument may be specified for any kind of template-parameter (type, non-type, template) that is not a template parameter pack (14.5.3). A default template-argument may be specified in a template dec-laration. A default template-argument shall not be specified in the template-parameter-lists of the definition of a member of a class template that appears outside of the member’s class. A default template-argument shall not be specified in a friend class template declaration. If a friend function template declaration specifies a default template-argument, that declaration shall be a definition and shall be the only declaration of the function template in the translation unit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With