문제

In C++ pure virtual classes are often used for runtime polymorphism.

So you have:

class IInterfaceA
{
    virtual void DoFoo() = 0;
};

And derived classes like:

class CFancyObject : public IInterfaceA
{
...

Which then can be used in functions like:

void Foo(IInterfaceA &interface);

But this is runtime case, and if the objects are known at compile time, we can do better by using CRTP:

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

class CFancyObject : public IInterfaceA<CFancyObject>
{
    ...
}

Is it possible to use CRTP based derived classes in functions that take IInterface as a parameter?

void Foo(IInterfaceA<?> &interface);
도움이 되었습니까?

해결책

An interface is meant to decouple the API of a class from its implementation. By introducing a template parameter you are tightly coupling the implementation to the interface, defeating the whole purpose. CRTP is meant to solve a different set of problems.

If you make the interface templated, the function that takes it as a parameter must be templated as well. Once you've done that there's no difference between using the interface class and using the implementation class.

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

is identical to and provides no advantages over

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

다른 팁

Couldn't you just do:

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) {...}
}

?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top