I have a 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 composite interface. The following code even is not compiled since it is “ambiguous” for G++ and MSVC to deduce which type of foo() is called. Could please anyone point me out how to make the code below compile and work? (unfortunately I have no time for refactoring).
And I even do not understand why the compiler cannot deduce what 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;
};
You need explicitly import
foointo theIface12class, so you’ll get two overloaded functionsIface12::foo.The member functions with the same name overload each other only when they are declared in the same class, if you want to overload an inherited function you need to import the name in the current class via
using ParentClass::functionName. I think this is principle of least surprise – your member function will not be overloaded unless you ask for it.