c++templatesvariadic-templatespolicy-based-design

Creating a class template which can take a class made from itself as an argument


Is there a way to create a class template which can take an instantiation of itself as a template argument?

I would like to be able to say something this in my code:

Operation<float> op1(0.3f);
Operation<float, Operation> op2(0.5f, op1);

I tried defining such a class template with a variadic template parameter to avoid ending up in an infinite loop (the template would have to define a template template parameter which takes a template parameter itself which also has to take a template parameter and so on...).

template<typename T, typename... OP>
class Operation{
    Operation(T pVal, OP... pOP);
    ...
};

typename... OP should be able to take an Operation<T> or even an Operation<T, Operation<T>>

Is this possible?

Context: I am trying to build policy based functors which can be combined to form arithmetic "chain reactions". One operation uses a Function policy class to determine what it should do and it will also take two Source objects as arguments. the source objects may either be Function policies or other Operations as both of these define the function T execute(). the final goal is to perform these arithmetic operations at runtime upon command by calling these functors.


Solution

  • You may use:

    template<typename T, typename... OP>
    class Operation{
        // ...
    };
    

    but usage would be

    Operation<float> op1(0.3f);
    Operation<float, Operation<float>> op2(0.5f, op1);