简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM