1

I am using private inheritance to model my has-a relationship, but my base class type is rather complicated (well, a little bit), and I would like to have a typedef for it. Is something like the following possible in C++

struct S : private typedef std::vector<int> Container {};

Currently I am doing:

template< typename Container = std::vector<int> >
struct S : private Container {};

But this

  • makes my class to a template class. This is not a big problem for my current application (since it is a template class anyway), but in general is not nice.
  • could lead to bugs, when people think they are allowed to specify their own container.
tommsch
  • 582
  • 4
  • 19

1 Answers1

1

Considering that:

you could prefer private composition:

struct S {
  using Container = std::vector<int>; // outside struct also possible
  private: Container container;  
};  

There is no code duplication here: with inheritance, you'd just have a container sub-object whereas with composition you'd have a container member, and both would use the same code.

There is no decisive advantage of private inheritance, since other classes could not use the public members defined in the base class. The only advantage is that you can use public members in the class definition, whereas with composition, you'll have to prefix the member with the object name.

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • In my real code, I do not inherit from std:: containers, but from my own ones. (I am writing a container for Cuda), and since Cuda-C++ is quite limited, I have a lot of SFINAE, and each member function is implemented roughly three times. Thus, private inheritance is much easier to work with from this point of view. – tommsch Jan 16 '23 at 09:24