Search code examples
c++templatestemplate-specialization

Private member of template class in the specialisation


I have a template class as following

template <typename T>
class Reader {
 public:
  Reader(std::string& filename, uint dummy_sid = 0) {...};
  bool isBroken() {return m_is_broken;}
  T getNext() {some operations; return m_event;}

 private:
  bool m_is_broken = false;
  uint m_dummy_sid = 0;
  T m_event;

};

And then I am creating two specialisations similar to the following one:

template<>
class Reader<NAME_A> {
 public:
  Reader(std::string& filename, uint dummy_sid = 0) {
    m_dummy_sid = dummy_sid;
    m_in_file = std::ifstream(filename);
  }
 private:
  std::ifstream m_in_file;
};

So I would like to add one private class member and redefining the constructor. During compilation it seems that for example in the specialisation the member m_dummy_sid is not seen (error: m_dummy_sid' was not declared in this scope; did you mean 'dummy_sid'?). Clearly this is not the way to specialise and extend one class I guess. What am I doing wrong?


Solution

  • First of all, the template specialization of class dualReader should have the same name as Reader.

    template<>
    class Reader<NAME_A> {
     public:
     .....
     .....
    };
    

    Secondly, the specialization of Reader template cannot the the members of non-specialized template Reader. This is because C++ actually threats the template specializations of classes as completely different types. The only relation it has to the original template is the name.

    For your problem inheritance is more suitable. You can inherit from Reader class

    template<class T>
    class dualReader : public Reader<T>{
     public:
     .....
     .....
     private:
     std::ifstream m_in_file;
    };
    

    Also if you want derived class to access the members of the base class, you should declare the members of the base class as protected.