Jump to content
  • Advertisement
Sign in to follow this  
AngleWyrm

Exposing base class in template

This topic is 3502 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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;
//...
};

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!