Using C++, how do I correctly inherit from the same base class twice?

前端 未结 8 1122
醉酒成梦
醉酒成梦 2020-12-29 10:35

This is our ideal inheritance hierarchy:

class Foobar;

class FoobarClient : Foobar;

class FoobarServer : Foobar;

class WindowsFoobar : Foobar;

class UnixF         


        
8条回答
  •  滥情空心
    2020-12-29 11:22

    You're in C++, you should get friendly with templates. Using the template-argument-is-a-base-class pattern, you'll not need any multiple inheritance or redundant implementations. It will look like this:

    class Foobar {};
    
    template  class UnixFoobarAspect : public Base {};
    template  class WindowsFoobarAspect : public Base {};
    template  class FoobarClientAspect : public Base {};
    template  class FoobarServerAspect : public Base {};
    
    typedef UnixFoobarAspect/*this whitespace not needed in C++0x*/> UnixFoobarClient;
    typedef WindowsFoobarAspect > WindowsFoobarClient;
    typedef UnixFoobarAspect > UnixFoobarServer;
    typedef WindowsFoobarAspect > WindowsFoobarServer;
    

    You might also consider using the curiously recurring template pattern instead of declaring abstract functions to avoid virtual function calls when the base class needs to call a function implemented in one of the specialized variants.

提交回复
热议问题