【问题标题】:can a templated member function implement two base classes's virtual functions?模板化的成员函数可以实现两个基类的虚函数吗?
【发布时间】:2014-03-12 01:59:50
【问题描述】:

我在这里遇到了一个奇怪的场景......我有一个对模板化基类进行多重继承的类,我想在我的最终派生类中实现一个模板化实现

模板化基础:

//simple class with a pure virtual function DoFoo()
template <typename T> 
struct foo
{
    virtual T DoFoo() = 0;
};

base2:

//a simple class that inherits from foo, but does not implemented DoFoo()
struct bar {};
struct base2 : public foo<bar> 
{

};

最终派生类:

//a class that inherits from base2, and foo<bar2>, 
//that needs an implementation of DoFoo for both bar and bar2 types. 
struct bar2{};
struct final : public base2, public foo<bar2> 
{
     template <T>
     T DoFoo(){ return T();}

};

我希望看到编译器会生成 struct final 必须实现的两个虚函数,一个用于 bar 和 bar2 的 DoFoo 版本。如果编译器能够看到,模板化函数应该是能够生成匹配两个虚函数原型的模板化函数。

但是,编译器似乎认为缺少用于 bar 和 bar2 的 DoFoo() 函数,并以 " 表示错误,因为以下虚函数是纯在 " 错误中的。

我在语法方面遗漏了什么吗?或者这是我在继承和模板方面遇到的不可能的情况?为什么?

【问题讨论】:

    标签: c++ templates inheritance


    【解决方案1】:

    但是,编译器似乎认为缺少用于 bar 和 bar2 的 DoFoo() 函数

    没错。 foo::DoFoo 命名一个 foo 成员函数。 final::DoFoo 命名成员模板,而不是成员函数。 final::DoFoo&lt;int&gt; 确实命名了一个成员函数,其定义是通过实例化该模板生成的,但该成员函数的名称是 final::DoFoo&lt;int&gt;——此时的尖括号只是其拼写方式的一部分。

    【讨论】:

    • 所以 dofoo 永远无法匹配 foo::dofoo() 的函数签名?我猜是因为生成的函数类型是模板参数化的,而虚函数不是?
    • @MichaelXu 没错,但我会说它是“因为生成的函数名称包含模板参数”。
    • 好吧,睡了一会儿,我觉得这更有意义.. final 中的模板是一个模板化的成员函数,而 foo 是一个带有成员函数的模板化类。这是两个不同的东西,编译器无法匹配
    猜你喜欢
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多