Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为不明确的重载函数调用创建默认值_C++_Inheritance_Overloading_Diamond Problem - Fatal编程技术网

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

C++ 为不明确的重载函数调用创建默认值,c++,inheritance,overloading,diamond-problem,C++,Inheritance,Overloading,Diamond Problem,我有一个具有重载方法的类。某个子类继承这两种类型。是否可以设置默认方法调用以避免调用static\u cast(obj) 有没有办法让编译器默认为某个方法调用 *接受聪明/优雅的变通方法 您可以使用模板为您执行静态\u cast,然后调用默认值: struct A {}; struct B { template<typename T> void foo(T& t) { foo(static_cast<A&>(t));

我有一个具有重载方法的类。某个子类继承这两种类型。是否可以设置默认方法调用以避免调用
static\u cast(obj)

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


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

您可以使用模板为您执行
静态\u 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)
}
struct A{};
结构B{
模板
空富(T&T){
foo(静态_-cast(t));
}
空富(常数A){
/*恳求*/
}
无效foo(const B){
/*恳求*/
}
};
结构C:A,B{
};
int main(){
C C;
B B;
b、 foo(c);//最终调用foo(A)
}

但是再次声明一个接受
C

的成员函数可能更容易,那么声明
void foo(const C)
以便调用默认函数如何?哦,对不起,foo是来自超类的方法调用,而C是子类。我将编辑我的问题以展示这一点。也许在发布之前尝试编译您的示例。有很多语法错误,这个问题现在令人困惑,因为如果
foo
是一个成员函数,就不能用这种方式调用它。好的,修复了它。投票选出了最佳、伟大的解决方案。我不知道你可以用这种方式使用模板而不使用菱形括号。我正在写一个数学库(带有操作符),所以不需要进行静态转换,或者对于干净的表示法来说非常棒。谢谢
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)
}