Reputation:
this question is related to c++
there is a library which declares a class named Solver < TS,FS >. Solver is a member of another class Domain (written by me)
now there are many Domains which have a member "int region"
what i want to do is depending on the value of region, I want to make the solver accept different arguments for TS and FS. I was thinking of something along the line
template<int region>
struct Decider
{
if(region==1)
{
typedef TSA TS;
typedef FSA FS;
}
else
if(region==2)
{
typedef TSB TS;
typedef FSB FS;
}
}
and later use it as
Decider<region>::TS
Decider<region>::FS
However, here due to the scope of the if, i guess the struct is useless. However, I am not able to think of a better method to do this. Any suggestions?
All the different TS and FS have the same interface. So I don't have to worry about the inside code.
Upvotes: 10
Views: 2994
Reputation: 13104
Note for anyone coming across this now:
It is also possible to do this with the boost libraries using the type_trait boost::conditional.
typedef boost::conditional<condition, type_if_true, type_if_false> MyTypeDef;
condition
still needs to be a compile time expression that evaluates to true or false. This also makes it so you don't need to specialize your entire class for just a few lines of differences.
Upvotes: 2
Reputation: 54584
If you need to parameterize Decider
based on some compile time constant, you can use template specialization (see other answers).
If you need to parameterize Decider
based on a runtime value of region
, you have to defer the parameterization to runtime as well. Usually this is done through some sort of creation function or factory idiom.
Upvotes: 5
Reputation: 54270
You need to use template specialisation.
template <int region>
struct Decider;
template <>
struct Decider<1>
{
typedef TSA TS;
typedef FSA FS;
};
template <>
struct Decider<2>
{
typedef TSB TS;
typedef FSB FS;
};
C++ will choose which version to use based on the region
supplied.
You can, of course, extend this as you see fit for other region numbers.
Upvotes: 9
Reputation: 99565
You can specialize a template for any region
value.
template<int region>
struct Decider;
template<>
struct Decider<1>
{
typedef TSA TS;
typedef FSA FS;
};
template<>
struct Decider<2>
{
typedef TSB TS;
typedef FSB FS;
};
Upvotes: 16