C++基模板类虚拟方法未出现在派生中?

C++ base template class virtual methods doesn't appear in derived?

本文关键字:派生 方法 虚拟 C++      更新时间:2023-10-16

以免考虑以下代码:

#include <iostream>
template <typename T_VAL>     // not used template argument
struct Foo {        int x;    };
template <typename T_VAL>
struct Bar {        int x;    };
template <typename T_VALUE>
struct A
{
    // just 2 overloaded data() members:
    virtual void data(Foo<T_VALUE>) {
        std::cout << "FOO EMPTYn";
    }
    virtual void data(Bar<T_VALUE>) {
        std::cout << "BAR EMPTYn";
    }
};

template <typename T_VALUE>
struct B : public A<T_VALUE>
{
    void data(Foo<T_VALUE>) {
        std::cout << "smart FOO impln";
    }
};

int main(void) {
    B<float> TheObject;
    Bar<float> bar;
    TheObject.data(bar); // I expect virtual base call here
    return 0;
}

编译器消息为:

tmpl.cpp: In function 'int main()':
tmpl.cpp:43:14: error: no matching function for call to 'B<float>::data(Bar<float>&)'
  TheObject.data(bar);
                    ^

void data(Bar<T_VALUE>) -> void data(Bar<T_VALUE>&) 不会改变任何东西

为什么派生的类 B 没有虚拟空数据(Bar&)?

另一个data是隐藏的。

template <typename T_VALUE>
struct B : public A<T_VALUE>
{
    using A<T_VALUE>::data; // Add this line
    void data(Foo<T_VALUE>) {
        std::cout << "smart FOO impln";
    }
};