Exposing base class in template

Started by
4 comments, last by Red Ant 14 years, 11 months ago
I want to specialize an STL vector<T> sort of like so
#include <vector>
template<class T>
class my_class : protected vector<T>
{
public:
    const size_t size(){ return vector<T>::size(); }
    //...
};

What I'de really like is for the size() function (and some others) from vector<T> to be public, but all the other stuff to be private (find, insert, etc) Is there some way to expose a select few base-class functions without declaring the whole vector<T> public?
--"I'm not at home right now, but" = lights on, but no ones home
Advertisement
Its pretty easy if you use composition over inheritance:
#include <vector>template<class T>class my_class{    typedef std::vector<T> Storage;    Storage data;public:    // note the "const".    const Storage::size_ttype size() const { return data.size(); }        // other functions here};

It is possible to do this with inheritance, but I wouldn't recommend it.
If you did it with inheritance it would look like:

template<class T>class my_class : protected std::vector<T>{public:    using std::vector<T>::size;    //...};
I thought inheriting from std containers was discouraged?
Innovation not reiterationIf at any point I look as if I know what I'm doing don't worry it was probably an accident.
Quote:Original post by Guthur
I thought inheriting from std containers was discouraged?


I can see how inheriting publicly from a STL container would be a bad idea (if someone has a pointer to std::vector<T> that actually points to a my_class<T>, they might end up calling the wrong destructor, since std::vector<T> doesn't have a virtual destructor). As far as I can see, what SiCrane did seems fine.
If one does use inheritance rather than composition, shouldn't you use private inheritance? I know that this means that you can no longer use your class polymorphically, but I thought that was the desired effect anyway.

This topic is closed to new replies.

Advertisement