Can you use CRTP and functions taking an interface as a parameter?
문제
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) {...}
}
?