1

I have a class which looks something like this. I'd prefer to have the typedef of ParentMember in the Parent class and rename it Member. How might this be possible? The only way I can see is to have std::vector as a public member instead of using inheritance.

typedef std::pair<std::string, boost::any> ParentMember;
class Parent: public std::vector<ParentMember>
{
public:
    template <typename T>
    std::vector<T>& getMember(std::string& s)
    {
        MemberFinder finder(s);
        std::vector<ParentMember>::iterator member = std::find_if(begin(), end(), finder);
        boost::any& container = member->second;
        return boost::any_cast<std::vector<T>&>(container);
    }
private:
    class Finder
    {
      ...
    };
};
Baz
  • 12,713
  • 38
  • 145
  • 268
  • 2
    You [shouldn't publicly inherit from std::vector](http://stackoverflow.com/questions/4353203/thou-shalt-not-inherit-from-stdvector). – juanchopanza Sep 13 '12 at 15:38
  • @juanchopanza `Actually, there is nothing wrong with public inheritance of std::vector. If you need this, just do that.` So... Why no? You shouldn't use polymorphism, since vector has no virtual d-tor, but inherit from vector is OK. – ForEveR Sep 13 '12 at 15:40
  • Could you also provide a code that would use your class (and Parent::Member type)? – UnknownGosu Sep 13 '12 at 15:41
  • @ForEveR if you have a clean way to stop polymorphism, then fine. – juanchopanza Sep 13 '12 at 15:51

1 Answers1

2

The only way I can see is to have std::vector as a public member instead of using inheritance.

Yeah... that's The Correct Way™.

Now let's assume the class in question is not std::vector but something else, which would make this a legitimate question.

One solution is to use the non-typedef version for the base class and then typedef it

class Parent
  : public std::vector<std::pair<std::string, boost::any>>
{
public:
  typedef std::pair<std::string, boost::any> Member;
  // ...
};

In case of std::vector as a base class, it even exposes the type as a nested value_type typedef, which would allow you to make sure the two are never different:

typedef value_type Member; // value_type inherited from std::vector

If your Parent class is a template itself, you would need

typedef typename Parent::value_type Member;
Xeo
  • 129,499
  • 52
  • 291
  • 397