c++templatestemplate-specializationscope-resolution-operator

How to create specialization template using scope resolution operator in cpp


template<class t> class Temp{
    static t x;
    public:
      Temp(){};
      t increment();
      ~Temp(){/*body of destructor is important.*/};
};

template<class t>t Temp<t>::x;

template<class t> t Temp<t>::increment(){
    return ++x;
}

/*Template specialization starts.*/
template<>class Temp<int>{
    int x;
    public:
      Temp():x(0){};
      int increment();
      ~Temp(){};
};
/*Below is the error part.*/
template<>int Temp<int>::increment(){
    return 0;
}

The problem is the last block of code. Compilation Error ->error: template-id 'increment<>' for 'int Temp::increment()' does not match any template declaration


Solution

  • You don't have to use template<> with specialized member function, because the compiler knows that you are specializing the Temp for int type. So an empty template<> giving the error.

    int Temp<int>::increment() {
      return ++x;
    }
    

    template is used to tell the compiler that T is template param, that's all. But in your case your are specializing for int type, so you don't have to specify template<>. template<> is applicable only for the class and not for member functions defining out side the class.