The below code couldn't pass the compilation, what's the consideration for this compiler error?
template<class T> void f(T t) {}; template<> void f<char>(char c = 'a') {}
Error message: Default arguments are not allowed on an explicit specialization of a function template
You cannot give default arguments to the same template parameters in different declarations in the same scope. The compiler will not allow the following example: template<class T = char> class X; template<class T = char> class X { };
Explicit (full) specializationAllows customizing the template code for a given set of template arguments.
Just like in case of the function arguments, template parameters can have their default values. All template parameters with a default value have to be declared at the end of the template parameter list.
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
I think that the rationale behind this error is due to the fact that the default arguments in the function template apply to its specialization as well and you are not allowed to define the default argument more than once in C++.
Consider the following:
#include <iostream> template<class T> void f(T t = 'a') {} template<> void f<char>(char c) { std::cout << c << std::endl; } int main(int argc, char **argv) { f<char>(); }
This will print a
meaning that specialization is called with the default argument defined in the main template.
If you need a different default argument for each specialization you can use the approach illustrated below:
#include <iostream> template<class T> struct default_arg { static T get() { return T(); } }; template<class T> void f(T t = default_arg<T>::get()) {} template<> struct default_arg<char> { static char get() { return 'a'; } }; template<> void f<char>(char c) { std::cout << c << std::endl; } int main(int argc, char **argv) { f<char>(); }
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