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

标签 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 
}

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

*接受聪明/优雅的解决方法。

最佳答案

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

关于c++ - 为不明确的重载函数调用创建默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45972423/

相关文章:

c++ - 未计算上下文中的 Lambda(需要表达式)

c++ - 无法将 QGraphicsView 坐标映射到 QGraphicsScene

ios - 如何解决过载问题?

c++ - 即使声明了变量也没有声明

java - 访问隐藏在第三个扩展类中的间接父类(super class)变量

iphone - self 和 super 的区别

c++ - 没有匹配的函数来调用 ..constructor

c++ - 有没有办法确保传递给函数的两个参数在 C++ 中被视为第一个和第三个参数?

模板参数上的 C++ 函数模板重载

c++ - 使用 Qt 将函数链接到计时器