Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explicit specialization of template class member function

I need to specialize template member function for some type (let's say double). It works fine while class X itself is not a template class, but when I make it template GCC starts giving compile-time errors.

#include <iostream> #include <cmath>  template <class C> class X { public:    template <class T> void get_as(); };  template <class C> void X<C>::get_as<double>() {  }  int main() {    X<int> x;    x.get_as(); } 

here is the error message

source.cpp:11:27: error: template-id   'get_as<double>' in declaration of primary template source.cpp:11:6: error: prototype for   'void X<C>::get_as()' does not match any in class 'X<C>' source.cpp:7:35: error: candidate is:   template<class C> template<class T> void X::get_as() 

How can I fix that and what is the problem here?

Thanks in advance.

like image 776
ledokol Avatar asked Apr 01 '11 11:04

ledokol


People also ask

What is explicit template specialization?

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

What is the syntax for explicit class specialization?

What is the syntax to use explicit class specialization? Explanation: The class specialization is creation of explicit specialization of a generic class. We have to use template<> constructor for this to work. It works in the same way as with explicit function specialization.

What is the difference between template class and template function?

For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.

When we specialize a function template it is called?

To do so, we can use a function template specialization (sometimes called a full or explicit function template specialization) to create a specialized version of the print() function for type double.


1 Answers

It doesn't work that way. You would need to say the following, but it is not correct

template <class C> template<> void X<C>::get_as<double>() {  } 

Explicitly specialized members need their surrounding class templates to be explicitly specialized as well. So you need to say the following, which would only specialize the member for X<int>.

template <> template<> void X<int>::get_as<double>() {  } 

If you want to keep the surrounding template unspecialized, you have several choices. I prefer overloads

template <class C> class X {    template<typename T> struct type { };  public:    template <class T> void get_as() {      get_as(type<T>());    }  private:    template<typename T> void get_as(type<T>) {     }     void get_as(type<double>) {     } }; 
like image 87
Johannes Schaub - litb Avatar answered Nov 15 '22 14:11

Johannes Schaub - litb