c++templatesgccspecializationclass-template

How do you define an explicit specialization for a member function of a class template?


I need to specialize a class template X's member function for some type (let's say double). It works fine while class X itself is not a class template, but when I make it a template, GCC starts giving compiler 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()

What is the problem here, and how can I fix it?


Solution

  • 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>) {
    
       }
    };