首页 > 代码库 > A template class that has a function for specific type

A template class that has a function for specific type

So you have a C++ template class, but you want to specifiy a member function for a particular type of data: 

 1 // A template class called Image:  2 template <class T> 3 class Image { 4 public: 5   // ======================== 6   // CONSTRUCTOR & DESTRUCTOR 7   Image() : width(0), height(0), data(NULL) {} 8   Image(const Image &image) : data(NULL) {  9     copy_helper(image); }10   const Image& operator=(const Image &image) { 11     if (this != &image)12       copy_helper(image);13     return *this; }14   ~Image() {15     delete [] data; 16   }17   bool Load(const std::string &filename);18 };19 20 // But you want to specify a function for a particular type:21 template <> // notice this is an empty arrow bracket22 bool Image<Offset>::Load(const std::string &filename) { // Offset is a class, you can specify Offset so you don‘t put a T in the arrow bracket23  ... // sth here24 }

 

A template class that has a function for specific type