为不明确的重载函数调用创建默认值

Creating a Default for ambiguous overloaded function call

我有一个 class 有一个重载方法。某个subclass继承了这两种类型。是否可以设置默认方法调用以避免必须调用 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 
}

有没有办法让编译器默认调用某个方法?

*Clever/elegant 变通办法已被接受。

您可以使用模板为您完成 static_cast,然后调用默认值:

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)
}

但是话又说回来,声明一个接受 C.

的成员函数可能会更容易