I want to perform a set of tests in my code that are similar but change only depending on a parameter.
I could write this using a switch statement:
bool doTest(EnumSensorFamily family, const StructSensorProposal& proposed)
{
switch (family)
{
case FAM1:
return (ExpectedFam1 == proposed.Fam1SensorId);
break;
case FAM2:
return (ExpectedFam2 == proposed.Fam2SensorId);
break;
case FAM3:
return (ExpectedFam3 == proposed.Fam3SensorId);
break;
default:
ERROR ("Unexpected family");
return false;
}
}
I was thinking of doing this with template specialisations
template <EnumSensorFamily family>
bool doTest(const StructSensorProposal& proposed);
template<>
bool doTest<FAM1> (const StructSensorProposal& proposed)
{
return (ExpectedFam1 == proposed.Fam1SensorId);
}
template<>
bool doTest<FAM2> (const StructSensorProposal& proposed)
{
return (ExpectedFam2 == proposed.Fam2SensorId);
}
template<>
bool doTest<FAM3> (const StructSensorProposal& proposed)
{
return (ExpectedFam3 == proposed.Fam3SensorId);
}
Is there any benefit of doing this apart from avoiding a switch statement containing near identical cases?
Ideally I would like to be able to write single method to reduce the maintenance overhead.
thanks
See Question&Answers more detail:os