Creating a Default for ambiguous overloaded function call

108 views Asked by At

I have a class that has an overloaded method. A certain subclass inherits both of these types. Is it possible to set a default method call to avoid having to call static_cast<class>(obj)

struct A {};
struct B {

   void foo(const A) {
     /*impl*/
    }

   void foo(const B) {
     /*impl*/
   }
};

struct C : A, B {

};

int main() {
    C c; 
    B b;
    b.foo(c); //ambiguous 
}

Is there any way to have the compiler default to a certain method call?

*Clever/elegant workarounds accepted.

1

There are 1 answers

1
wally On BEST ANSWER

You could use a template to do the static_cast for you and then call the default:

struct A {};
struct B {

    template<typename T>
    void foo(T& t) {
        foo(static_cast<A&>(t));
    }

    void foo(const A) {
        /*impl*/
    }

    void foo(const B) {
        /*impl*/
    }
};

struct C : A, B {

};

int main() {
    C c;
    B b;
    b.foo(c); //eventually calls foo(A)
}

But then again it might just be easier to declare a member function that takes C.