虚拟模板成员类的变通方法
Virtual templates members of class workaround
假设我想为容器实现一些类。它们都应该实现插入、删除等功能。所以我写了一些接口:
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
成员函数变为虚函数,并让每个具体实现覆盖它们。
相关文章:
- 为什么在C++中首先初始化成员类
- 如何让qDebug编写方法和类名?
- 在 C++ 中使用模板方法重写类方法
- 如果方法在类中定义,则阻止编译器删除方法
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 我是否应该在包含虚拟方法的类上使用'memcpy'?如果没有,如何替换它?
- 非虚拟基的多态成员类
- 将带有模板化方法的类作为带有GCC的模板参数传递
- 当从成员类调用封装的std::begin时,程序崩溃
- 从私有成员类中断封装派生的模板类
- 调用虚拟成员类的方法
- 如何使用 "get" 方法返回类的私有 std::unique_ptr 成员
- 如何在不创建实例的情况下获取类的方法成员的类型?
- 我怎么可能从尚未定义某些成员方法的类创建实例?(C++)
- 如何仅通过类方法修改类公共数据成员
- 如何从方法访问类成员
- 如何使用派生类特定的方法:派生类中的派生成员
- 如何传递带有虚方法的类,以及如何将其作为成员变量使用
- 虚拟模板成员类的变通方法
- 对类的静态方法成员的未定义引用