Is it okay to inherit implementation from STL containers, rather than delegate?

前端 未结 7 1152
一生所求
一生所求 2020-11-22 07:15

I have a class that adapts std::vector to model a container of domain-specific objects. I want to expose most of the std::vector API to the user, so that they may use famili

7条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 07:39

    You can combine private inheritance and the 'using' keyword to work around most of the problems mentioned above: Private inheritance is 'is-implemented-in-terms-of' and as it is private you cannot hold a pointer to the base class

    #include 
    #include 
    
    class MyString : private std::string
    {
    public:
        MyString(std::string s) : std::string(s) {}
        using std::string::size;
        std::string fooMe(){ return std::string("Foo: ") + *this; }
    };
    
    int main()
    {
        MyString s("Hi");
        std::cout << "MyString.size(): " << s.size() << std::endl;
        std::cout << "MyString.fooMe(): " << s.fooMe() << std::endl;
    }
    

提交回复
热议问题