[英]CRTP - Is it possible to make an abstract base class?
我正在实现静态多态性:
template<typename T>
class Base {
public:
void method() {
// do something
impl();
// do something else
}
void impl() { // intended to be private
static_cast<T*>(this)->impl();
}
};
class Derived : public Base<Derived> {
public:
void impl() { // intended to be private
}
};
该代码是动态多态类的静态实现,其中void impl()
是纯虚拟的。 因此,基类是抽象的。
现在,这些类实现了静态多态性,因此没有纯虚函数。
是否可以使Base类抽象化,以便不能创建此类的对象?
您可以使用受保护的析构函数和构造函数:
template<typename T>
class Base {
public:
void method() {
// do something
impl();
// do something else
}
void impl() { // intended to be private
static_cast<T*>(this)->impl();
}
protected:
Base() = default;
~Base() = default;
// If you don't want to implement proper copying/moving:
// Base(const Base&) = delete;
// Base(Base&&) = delete;
// Base& operator=(const Base&) = delete;
// Base& operator=(Base&&) = delete;
};
这甚至将禁止派生类的成员函数创建基类对象,以及尝试删除静态类型为Base<T>
的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.