gpt4 book ai didi

c++ - 模板化的成员函数可以实现两个基类的虚函数吗?

转载 作者:行者123 更新时间:2023-12-01 15:03:10 28 4
gpt4 key购买 nike

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

模板化基础:

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

基地2:
//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 版本。模板化函数,如果编译器能够看到它,应该能够生成匹配两个虚函数原型(prototype)的模板化函数。

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

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

最佳答案

However, it appears as though the compiler believes that the DoFoo() functions, for bar and bar2 are missing



这是正确的。 foo::DoFoo命名为 foo成员函数。 final::DoFoo命名成员模板,而不是成员函数。 final::DoFoo<int>确实命名了一个成员函数,其定义是通过实例化该模板生成的,但成员函数的名称是 final::DoFoo<int> -- 那个时候的尖括号只是它的拼写方式的一部分。

关于c++ - 模板化的成员函数可以实现两个基类的虚函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22340508/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com