In the following code:
template <typename T>
class CRTP
{
public:
};
template <int I, typename T>
class CRTPInt
{
public:
};
template <template <typename> class T>
class Derived : public T<Derived<T>>
{
public:
};
void main()
{
Derived<CRTP> foo;
Derived<CRTPInt<2>> foo2;
}
How do I write CRPTInt so I can pass in a templatized parameter that will then be continued in the Derived definition?
Thanks,
Jim
The CRTP pattern is typically used to enable static polymorphism and the ability to mixin (parametrized) behavior. To illustrate two alternatives, it’s convenient to first define a general template
Then you define an interface class template for the type of behavior that you want
To get different implementations of this interface, simply define different classes that each derive from
FooInterfacewith themselves as curiously recurring template parameters:The alternative is to parametrize the different implementations of an interface. This time, the class template depends on both a template-template parameter and a non-type parameter
The implementation is then another class template, which derives from the interface with both itself and the non-type parameter as arguments
This is how you call them:
The classes in your question don’t quite fit into this general pattern. If you might want to give
Derivedsome CRTP-like behavior, then you can either doUPDATE: Based on the discussion from https://stackoverflow.com/a/11571808/819272, I discovered that the original answer only compiled on Visual Studio 2010, but not on gcc because of some Microsoft-specific, non-portable features. E.g. the
self()function fromenable_down_castis a (template) dependent name in its derived classes, and therefore not visible without explicitusingdirectives. Furthermore, I have added defaulted destructors with the right level of protection. Finally, I have renamed my original classenable_crtptoenable_down_castbecause that is precisely what it does: manually enable for static polymporphism what the compiler does automatically for dynamic polymorphism.