虚拟模板成员类的变通方法

Virtual templates members of class workaround

本文关键字:方法 成员类 虚拟      更新时间:2023-10-16

假设我想为容器实现一些类。它们都应该实现插入、删除等功能。所以我写了一些接口:

template <class T>
class ContainerInterface {
public:
   virtual void insert(T element) = 0;
   template<class Predicate>
   virtual void remove(Predicate p) = 0; 
};

现在我可以这样写:

template <class T>
class MyVector : public ContainerInterface<T>{};
template <class T>
class MyList : public ContainerInterface<T>{};

我确信MyVector和MyList必须实现插入和删除函数。但是,有错误:

error: templates may not be ‘virtual’

它来自:

template<class Predicate>
virtual void remove(Predicate p) = 0; 

我不知道谓词当我定义一些容器,我不认为绑定deleter对象到容器类有任何意义,例如,一次我可以传递谓词来删除小于50的整数,另一次我想删除偶数整数。在这种情况下可以做什么-在基类中声明一些模板化的东西并模拟函数的虚拟行为?

可以对函数对象使用类型擦除。但幸运的是,适当的设施已经存在!例如,在您的情况下,您可以使用boost::function<bool(const T&)>std::function<bool(const T&)>(具有TR1/c++ 11支持)作为谓词类型!

virtual void remove(std::function<bool(const T&)> p);

创建一些抽象的class Predicate,所有具体的谓词都必须继承。然后,只需将谓词作为函数的参数:

virtual void remove(Predicate* p) = 0;

当然,您必须使相关的Predicate成员函数变为虚函数,并让每个具体实现覆盖它们。