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

105 Views Asked by At

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.

2

There are 2 best solutions below

1
Jarod42 On BEST ANSWER

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);
0
dbencs On

http://en.cppreference.com/w/cpp/language/template_parameters

A template argument for a template template parameter must be an id-expression which names a class template or a template alias.

When the argument is a class template, only the primary template is considered when matching the parameter. The partial specializations, if any, are only considered when a specialization based on this template template parameter happens to be instantiated.

I hope this helps in your problem. Look for "Template template arguments".