【问题标题】:C++ base template class virtual methods doesn't appear in derived? [duplicate]C++ 基模板类虚拟方法没有出现在派生中? [复制]
【发布时间】:2016-01-27 19:56:04
【问题描述】:

免得考虑以下代码:

#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 EMPTY\n";
    }

    virtual void data(Bar<T_VALUE>) {
        std::cout << "BAR EMPTY\n";
    }
};


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


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&lt;T_VALUE&gt;) -> void data(Bar&lt;T_VALUE&gt;&amp;) 不会改变任何东西

为什么派生类B没有virtual void data(Bar&)?

【问题讨论】:

    标签: c++ templates inheritance g++ template-meta-programming


    【解决方案1】:

    另一个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 impl\n";
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 2013-10-07
      • 2016-04-12
      • 2014-03-22
      相关资源
      最近更新 更多