Erik Wikström wrote:
Quote:
Templates are a compile-time construct. You can not use any information
that is not known at compile-time when instantiating them.
>
I'm well aware of this, but I thought the compiler could use the limited
amount of available choices for each template argument to generate all
neccessary versions of the class and instanciate the correct one
depending on the user input.
Basically I was looking for a way to shorten code like this
if (input_choice_A == 1) {
if (input_choice_B == 1) {
some_class<firstA,firstBinstance();
// redundant code
} else {
some_class<firstA,secondBinstance();
// redundant code
}
} else {
if (input_choice_B == 1) {
some_class<secondA,firstBinstance();
// redundant code
} else {
some_class<secondA,secondBinstance();
// redundant code
}
}
Of course, instead of inserting the redundant code each time, you could
write a templated function like this:
template<typename Atype, typename Btype>
void run(some_class<Atype, Btype&instance) {
// Redundant code here only once
}
So it seems to be technically possible to make template values dependent
on user input. But - and this is what really concerns me - I'd need to
define each combination of template arguments manually, which is a LOT
in my case. It would be much shorter (and easier maintainable) if I
could define them in a way as illustrated here
if (input_choice_A == 1)
typedef firstA first_argument; // I know this won't be visible from
outside the if construct
else
typedef secondA first_argument;
if (input_choice_B == 1)
typedef firstB second_argument;
else
typedef secondB second_argument;
And then just instanciate the class with
some_class<first_argument, second_argumentinstance();
The advantage of such a technique becomes more and more obvious the more
combinations for the template arguments there are.
Regards,
Thomas