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

时间:2017-08-31 02:44:52

标签: c++ inheritance overloading diamond-problem

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

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

*接受了聪明/优雅的变通方法。

1 个答案:

答案 0 :(得分:1)

您可以使用模板为您执行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的成员函数可能更容易。