I have this problem here that I can’t figure out how to solve. I want a template class that takes an integer as template parameter and sets the template parameters for another class accordingly:
template <int T>
class Solver
{
public:
#if T <= 24
typedef MyMatrix<float> Matrix;
#else if T <= 53
typedef MyMatrix<double> Matrix;
#else
typedef MyMatrix<mpreal> Matrix;
#endif
Matrix create();
};
And then calling it like this:
Solver<53>::Matrix m = Solver<53>::create();
How can I do something like this? At the moment with the code above, the compiler complaints that it doesn't know "Matrix", so I'm not sure if you can use the preprocessor on template parameters.
No, you can't use the preprocessor on template parameters.
The preprocessor is just doing very simple string processing on your input source. It has no glue about types and I think it is run as the very first step while first processing the file and collecting all the includes. Templates are something the compiler itself takes care of. At this point the preprocessor has finished already.
A similar question has been asked here: Use a template parameter in a preprocessor directive?
You can use
std::conditional
for this, although whether you should be doing this in the first place is another kettle of fish:You'll need to use
std::conditional
and::type
instead ofconditional_t
if your compiler doesn't support it.INTRODUCTION
Since you'd like
S<N>::Matrix
to yield a different type depending on the N passed, you will need to use some sort of meta template programming. The question is currently tagged with preprocessor, and the snippet explicitly tries to use it; but that is of little to no use in this case.When the code is being preprocessed
N
is nothing more than a name, it hasn't got a value; yet.Solution
The description mentiones if, if ... else, and else; and we are dealing with types.. looking through
<type_traits>
it seems likestd::conditional
would be a perfect match!Note: Depending on whether the expression found in
condition
yields true, or false,::type
will be a typedef for either type-if-true, or type-if-false.Let's write a sample implementation: