在 C++ 中,纯虚拟类通常用于运行时多态性。
所以你有了:
class IInterfaceA
{
virtual void DoFoo() = 0;
};
和派生类,如:
class CFancyObject : public IInterfaceA
{
...
然后可以在以下功能中使用:
void Foo(IInterfaceA &interface);
但这是运行时情况,如果在编译时知道对象,我们可以使用 CRTP 做得更好:
template<class T> class IInterfaceA
{
public:
void DoFoo()
{
static_cast<T*>(this)->CallDerivedFunction();
}
}
class CFancyObject : public IInterfaceA<CFancyObject>
{
...
}
是否可以在将 IInterface 作为参数的函数中使用基于 CRTP 的派生类?
void Foo(IInterfaceA<?> &interface);