是否可以使用CRTP在静态多态中模拟纯虚函数? [英] Is emulating pure virtual function in static polymorphism using CRTP possible?
问题描述
我正在尝试使用CRTP实现编译时多态性,并希望强制派生类实现该功能.
I'm trying to implement compile-time polymorphism using CRTP, and want to force the derived class to implement the function.
当前的实现是这样的.
template <class Derived>
struct base {
void f() {
static_cast<Derived*>(this)->f();
}
};
struct derived : base<derived>
{
void f() {
...
}
};
在此实现中,如果派生类未实现 f()
,则对该函数的调用会陷入无限循环.
In this implementation, call to the function falls into an infinite loop if the derived class didn't implement f()
.
如何强制派生类实现类似于纯虚函数的函数?我尝试使用像 static_assert(& base :: f!=& Derived :: f,"...")
这样的"static_assert",但是它会生成一条错误消息,指出两个成员函数指针指向不同类的成员函数是不可比的.
How do I force the derived class to implement the function like pure virtual function? I tried to use 'static_assert' like static_assert(&base::f != &Derived::f, "...")
but it generates an error message saying that two member function pointers pointing to the different classes' member functions are not comparable.
推荐答案
您可以为您覆盖的内容和钩子赋予不同的名称,如下所示:
You can give the thing you override and the hook different names, like this:
template <class Derived>
struct base {
void f() {
static_cast<Derived*>(this)->fimpl();
}
void fimpl() = delete;
};
struct derived : base<derived> {
void fimpl() { printf("hello world\n"); }
};
在这里, fimpl = delete
在基部中,因此除非在派生类中覆盖了 fimpl
,否则它不会被意外调用.
Here, fimpl = delete
in the base so that it cannot be called accidentally unless fimpl
is overridden in the derived class.
您还可以将中间隐藏层粘贴到CRTP中,以临时"将 f
标记为 delete
:
You can also stick an intermediate hiding layer into your CRTP to "temporarily" mark f
as delete
:
template <class Derived>
struct base {
void f() {
static_cast<Derived*>(this)->f();
}
};
template <class Derived>
struct intermediate : base<Derived> {
void f() = delete;
};
struct derived : intermediate<derived> {
void f() { printf("hello world\n"); }
};
这篇关于是否可以使用CRTP在静态多态中模拟纯虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!