I have a lot of code like this:
#define WITH_FEATURE_X
struct A {
#ifdef WITH_FEATURE_X
// ... declare some variables Y
#endif
void f ();
};
void A::f () {
// ... do something
#ifdef WITH_FEATURE_X
// ... do something and use Y
#else
// ... do something else
#endif
// ... do something
}
and I'd like to replace the #defines with template parameters:
template < int WITH_FEATURE_X > // can be 0 or 1
struct A;
But I don't want to duplicate almost the entire code of A::f() for A<0>::f() and A<1>::f() just for the few lines that depend on the parameter. I also don't want to call functions instead of the previous #ifdefs. What is the common solution?
I believe what you want is an equivalent to the "static if" command that exists in D language. I am afraid such a feature does not exist in C++.
Note that if parts of your code vary depending on the feature your request, these parts don't belong in the main function because they are not part of the bare algorithm. So the option to delegate such features in functions seems like a good one.
EDIT
If your #ifdef statements are used to do the same subtask differently, then defining subfunctions is the right thing to do. It will make your code more readable, not less.
If they are used for completely different actions, well, your code is already cluttered. Do something about it.
As for the performance issue you fear might appear, trust your compiler.
EDIT2
I forgot to mention the answer to the first part of your code : use the following trick to add or remove members depending on "feature".
namespace helper
{
template<int feature>
struct A;
template<>
struct A<0> { // add member variables for case 0 };
template<>
struct A<1> { // add member variables for case 1 };
}
template<int feature>
class A : private helper::A<feature>
{
// ... functions here
};