2

在 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);
4

2 回答 2

2

接口旨在将类的 API 与其实现分离。通过引入模板参数,您将实现与接口紧密耦合,从而违背了整个目的。CRTP旨在解决一组不同的问题。

如果您将接口模板化,则将其作为参数的函数也必须模板化。一旦你这样做了,使用接口类和使用实现类就没有区别了。

template<class T>
void Foo(IInterfaceA<T> &interface) { interface.DoFoo(); }

template<class T>
void Foo(T &object) { object.DoFoo(); }
于 2012-02-16T17:07:32.810 回答
0

你不能这样做:

template<class T> class IInterfaceA 
{
public:
    template<class T2>
    void DoFoo(IInterfaceA<T2> &interface)
    {    
        static_cast<T*>(this)->CallDerivedFunction(interface);
    }
}

class CFancyObject : public IInterfaceA<CFancyObject>
{
    template<class T2>
    CallDerivedFunction(IInterfaceA<T2> &interface) {...}
}

?

于 2012-02-16T19:33:59.317 回答