views:

111

answers:

1

I'm looking for a clean way of doing this since a long time. In my problem, there exist 3 classes not sharing any parent in common but each having some methods with the same name (A.doSomething, B.doSomething, C.doSomething). Hence, having the same function signature, class D inheriting from A and using method doSomething() will "look the same" to E inheriting from B or C .

Here is a sketch of what I'd like to be able to do:

class Base {
    public:
    void myMethod(void) { doSomething(); }
};

class Independent {
    public:
        doSomething();
};

clase Derived : public Base : public Independent {
 (...)
};

int main(void) {
   Derived *derivedObject = new Derived();
   derivedObject->myMethod();
}

In this problem, object of type "Independent" is provided by a library that I cannot change. I would like to define a base class that uses methods that are going to be inherited later on. I couldn't find a proper way of doing this using virtual inheritance without causing ambiguous compiling.

+5  A: 

You've got a nasty situation there. One solution to this would be using the Curiously Recurring Template Pattern to perform the inheritance at compile-time, like this:

template <typename D>
class Base {
    public:
        void myMethod(void) { static_cast<D*>(this)->doSomething(); }
};

class Independent {
    public:
        void doSomething();
};

clase Derived : public Base : public Independent {
    /*...*/
};

int main(void) {
   Derived *derivedObject = new Derived();
   derivedObject->myMethod();
}

Alternatively, you could choose to put a middleman class in between to forward to Independent (I assume you have many classes deriving from the same Base and Independent, and just don't want to have to do this for each class).

template <typename D>
class Base {
    private:
        virtual void doSomethingImpl();
    public:
        void myMethod(void) { doSomethingImpl(); }
};

class Independent {
    public:
        void doSomething();
};

class IndependentWrapper : public Base : public Independent {
    private:
        void doSomethingImpl() { Independent::doSomething(); }
};

clase Derived : public IndependentWrapper {
    /*...*/
};

int main(void) {
   Derived *derivedObject = new Derived();
   derivedObject->myMethod();
}
coppro