考虑以下标准CRTP例如:保护CRTP模式调用
#include <iostream>
template<class Derived>
struct Base {
void f() { static_cast<Derived *>(this)->f(); }
void g() { static_cast<Derived *>(this)->g(); }
};
struct Foo : public Base<Foo> {
void f() { std::cout << 42 << std::endl; }
};
int main() {
Foo foo;
foo.f(); // just OK
foo.g(); // this will stack overflow and segfault
}
如果这是常规虚拟继承我能有标记的虚拟f
和g
方法为纯像
struct Base {
virtual void f() = 0;
virtual void g() = 0;
};
并得到关于Foo
抽象的编译时错误。但是CRTP没有提供这种保护。我能以某种方式实施它吗?运行时检查也是可以接受的。我想过比较this->f
指针与static_cast<Derived *>(this)->f
,但没有设法使其工作。
我不知道这是否是标准定义的行为,但是您可以在'Base :: g'内'static_assert'指定'&Derived :: g!=&Base :: g'。 –
Holt
这似乎也工作:http://coliru.stacked-crooked.com/a/80021ad0bfb7aa47 –
@ JohannesSchaub-litb这很聪明!你应该写一个答案。 – Yakk