Inheritance overload methods in C ++

I have legacy code:

struct Iface1 { virtual ~Iface1() {} virtual void foo(const int arg1) const = 0; }; struct Iface2 { virtual ~Iface2() {} virtual void foo(const int arg1, const int arg2) const = 0; }; /// Composite interface struct Iface12 : Iface1, Iface2 { }; 

I need to create a decorator for a composite interface. The following code has not even been compiled since it is "ambiguous" for g ++ and MSVC to deduce what type of foo () is being called. Can someone tell me how to make the code below, compile and work? (unfortunately, I do not have time to refactor).

And I don’t even understand why the compiler cannot deduce which function to call, since all function signatures are explicit. Thanks.

 struct IfaceDecorator : Iface12 { IfaceDecorator(Iface12& iface) : impl(iface) {} virtual void foo(const int arg1) const { impl.foo(arg1); } virtual void foo(const int arg1, const int arg2) const { impl.foo(arg1, arg2); } private: Iface12& impl; }; 
+7
source share
2 answers

You need to explicitly import foo into the Iface12 class, so you will get two overloaded Iface12::foo functions.

 struct Iface12 : Iface1, Iface2 { using Iface1::foo; using Iface2::foo; }; 

Member functions with the same name overload each other only when they are declared in the same class, if you want to overload the inherited function, you need to import the name in the current class through using ParentClass::functionName . I think this is the principle of least surprise - your member function will not be overloaded unless you ask for it.

+6
source

If the problem is related to the impl message, you can fix it with:

 impl.Iface1::foo( arg1 ); // ... impl.Iface2::foo( arg1, arg2 ); 

... etc.

EDITED: I tested it, and the uncertainty is over.

+2
source

All Articles