【问题标题】:Class template multiple inheritance and function overloading类模板多重继承和函数重载
【发布时间】:2016-02-10 10:53:43
【问题描述】:

为什么main下面的waitForEvent函数调用不明确?

#include <iostream>
struct Event1 { char c1[1]; };
struct Event2 { char c2[2]; };

template<class Event> struct EventSource
{    
    void waitForEvent(Event e) { std::cout << sizeof(e) << "\n"; };
};

typedef EventSource<Event1> Event1Source;
typedef EventSource<Event2> Event2Source;

struct Event12Source : public Event1Source, public Event2Source {};

int main()
{
    Event12Source source;

    source.waitForEvent(Event1());
    source.waitForEvent(Event2());

    return 0;
}

编译它我得到以下错误:

user@AHERLADUSERVM2:~/test/TemplateMultipleMethodInheritance$ g++ test.cpp  test.cpp: In function ‘int main()’: test.cpp:19:12: error: request for member ‘waitForEvent’ is ambiguous
     source.waitForEvent(Event1());
            ^ test.cpp:7:10: note: candidates are: void EventSource<Event>::waitForEvent(Event) [with Event = Event2]
     void waitForEvent(Event e) { std::cout << sizeof(e) << "\n"; };
          ^ test.cpp:7:10: note:                 void EventSource<Event>::waitForEvent(Event) [with Event = Event1] test.cpp:20:12: error: request for member ‘waitForEvent’ is ambiguous
     source.waitForEvent(Event2());
            ^ test.cpp:7:10: note: candidates are: void EventSource<Event>::waitForEvent(Event) [with Event = Event2]
     void waitForEvent(Event e) { std::cout << sizeof(e) << "\n"; };
          ^ test.cpp:7:10: note:                 void EventSource<Event>::waitForEvent(Event) [with Event = Event1]

(为什么)这不是函数重载解析的简单案例吗?

谢谢, 达米安

【问题讨论】:

  • using Event1Source::waitForEvent; using Event2Source::waitForEvent; 添加到派生类的主体中
  • 谢谢@PiotrSkotnicki,现在它可以工作了。你能解释一下为什么需要这些吗?
  • @DamianBirchler 因为Event2Source 在继承顺序中较晚,并且与任何继承的类一样,它隐藏了在继承顺序中位于它之前的具有相同名称的函数。执行 Piotr 建议的操作会告诉编译器将所有其他重载从指定类中剔除到当前类中,从而取消自动隐藏。

标签: c++


【解决方案1】:

这可能不是你想要的,但它会解决歧义

source.EventSource<Event1>::waitForEvent(Event1());
source.EventSource<Event2>::waitForEvent(Event2());

另外,如果您想为 Event1 和 Event2 添加基类,请注意this

【讨论】:

    【解决方案2】:

    因为重载不适用于继承。派生类从两个模棱两可的基类继承了相同的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多