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.
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;
};
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.
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.
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.
精彩评论