template parameters, #define and code duplication

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
};

如果你想避免重复函数f的逻辑,你可以使用模板方法模式(不,不是那种类型的template

template <bool enabled>
class helper {
protected:
    void foo() { /* do nothing */ }
};

template <>
class helper<true> {
protected:
    Y y;
    void foo() { /* do something with y */ }
};

struct A : private helper<WITH_FEATURE_X> {
    void f() {
        // common stuff

        foo(); // optimized away when WITH_FEATURE_X is false

        // more common stuff
    }
};

The common solution, is just to use #ifdef I'm afraid. :-)

链接地址: http://www.djcxy.com/p/2594.html

上一篇: 基于ASP.NET的授权

下一篇: 模板参数,#定义和代码重复