-1

我一直在阅读有关此主题的不同问题,但无法找到一个完全回答我正在寻找的问题。这是我拥有的代码模式:

class Base {
public:
    virtual void foo(int) const {...}
}

template <class T>
class TmplClass : public Base {
public:
    virtual void foo(int i) const { foo(T(i)); }
    virtual void foo(T& param) const {
        printf("Template::Foo\n");
        bar(param);
    }
    virtual void bar(T&) const {
        printf("Template::Bar\n");
    }
}

class Derived : public TmplClass<SomeConcreteType> {
public:
    void bar(SomeConcreteType&) {
        printf("Derived::Bar\n");
    }
}

int main() {
    Derived d;
    Base* b = &d;
    b->foo(1);
}

执行时我得到:

Template::Foo
Template::Bar

为什么调用 bar 的运行时调度不起作用?如果我在 Derived 中重载 foo 那么它确实调用了 foo 的派生版本,为什么它不能为 bar 执行动态调度?

因为我正在使用现有代码,所以我不希望在这里更改类的基本结构。我希望能找到一种方法来使通话正常工作,或者了解为什么不能正常通话。基于在这里阅读其他问题,我尝试了很多不同的事情,但都无济于事。

4

1 回答 1

1

Turns out this wasn't a template issue. The problem with the code is that the Derived::bar method is not marked as const where-as the TmplClass::bar method is marked const. So, the intention was to provide an over-ride, but actually Derived::bar is a totally different method with a different signature, so that's why it was giving un-expected behavior. Once the const is removed from TmplClass::bar or added to the Derived::bar then the signatures match and the expected output is received:

Template::Foo
Derived::Bar
于 2013-12-11T17:44:21.510 回答