在C++中,纯虚拟类通常用于运行时多态性。您可以使用CRTP和将接口作为参数的函数吗?
所以,你必须:
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);
难道你不能只有一个非模板化的基础接口,模板化接口从中继承吗? – Nick 2012-02-16 17:03:01
@Nick:但它必须调用派生类的成员函数,它必须在编译时计算。我不太清楚如何在代码中描述。 – Coder 2012-02-16 17:05:35