Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why default argument cannot be specified for an explicit template specialization?

Tags:

c++

templates

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

like image 727
Thomson Avatar asked Oct 29 '10 08:10

Thomson


People also ask

CAN default arguments be used with the 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 { };

What is explicit template specialization?

Explicit (full) specializationAllows customizing the template code for a given set of template arguments.

Can template parameters have default values?

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.

What is the purpose of default function argument?

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.


1 Answers

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>(); } 
like image 132
vitaut Avatar answered Oct 14 '22 18:10

vitaut