当孩子为模板时,请从父母致电子方法

Call child method from parent, when child is a template

本文关键字:父母 子方法 孩子      更新时间:2023-10-16

我有一个大学项目,我必须使用模板创建一个binarysearchtree类。我们必须读取文件并根据文件中的数据类型创建树。我为树上称为BST的树做了一个父班,因此我可以在不给它提供类型的情况下使用树。

class BST{
    public:
        BST();
        ~BST();
}

和树

template <class T> class BinarySearchTree : public BST{
    public:
        void add(T val);
}

我想这样做:

BST tree = BinarySearchTree<int>(); //just an example, it can be of any type
tree.add(5); //doesn't work

如何在不提供特定变量类型的情况下从BST调用"添加"?

您必须在类BST中制作虚拟方法,并使BST成为模板。

virtual void add(T val) = 0;

使用crtp(奇怪的是恢复/接收模板模式)和概念模式。

https://qiita.com/riyaaaa_a/items/a9af401520f238f45b80

这是用日语编写的,但是很有趣!