在多个基类中重载成员函数 [英] Overloading member function among multiple base classes

查看:116
本文介绍了在多个基类中重载成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我希望具有多个名称相同但签名不同的成员函数,并散布在多个基类中.

Basically I want to have multiple member functions with same name, but different signature, spread in multiple base classes.

示例:

#include <iostream>

struct A
{
    void print(int) { std::cout << "Got an int!" << std::endl; }
};

struct B
{
    void print(double) { std::cout << "Got a double!" << std::endl; }
};

struct C : A, B {};

int main()
{
    C c;
    c.print((int)0);

    return 0;
};

但是我在clang上遇到了这个错误:

But I got this error on clang:

main.cpp:18:7: error: member 'print' found in multiple base classes of different types
    c.print((int)0);
      ^
main.cpp:5:10: note: member found by ambiguous name lookup
    void print(int) { std::cout << "Got an int!" << std::endl; }
         ^
main.cpp:10:10: note: member found by ambiguous name lookup
    void print(double) { std::cout << "Got a double!" << std::endl; }

为什么模棱两可?即使使用不同数量的参数,我也会遇到相同的错误.

Why is it ambiguous? Even with different number of arguments I get the same error.

是否有任何变通方法来获得类似的行为?

Is there any workaround to get similar behavior?

推荐答案

在派生类中使用using声明-这样可以解决您的问题.它使重载 visible和都可以参与决议.

Use a using declaration in the derived class - it will fix your issues. It makes both overloads visible and viable to participate in the resolution.

struct C : A, B {
    using A::print;
    using B::print;
};

要回答为什么这是模棱两可的:实际上,这与 visibility 无关,而是与参加重载解决方案有关,因为没有在相同的定义中定义范围. using声明将那些方法拉到C范围内,因此它们都成为有效的重载解决方案选项.

To answer why this is ambiguous: it is actually not about visibility, but about the inability to participate in the overload resolution, due to not being defined in the same scope. The using declaration pulls those methods in the C scope, so both of them become valid overloading resolution options.

感谢 @Pete Becker 参与了此答案,并为此创建了一个段落.

Thanks to @Pete Becker for participating in this answer and pretty much creating this paragraph.

这篇关于在多个基类中重载成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆