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