#include <vector>
template<class T>
class my_class : protected vector<T>
{
public:
const size_t size(){ return vector<T>::size(); }
//...
};
Exposing base class in template
I want to specialize an STL vector<T> sort of like so
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?
Its pretty easy if you use composition over inheritance:
It is possible to do this with inheritance, but I wouldn't recommend it.
#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; //...};
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
Popular Topics
Advertisement