模板参数、#define 和代码重复

2024-03-18

我有很多这样的代码:

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

我想用模板参数替换#defines:

template < int WITH_FEATURE_X > // can be 0 or 1
struct A;

但我不想为 A::f() 和 A::f() 复制 A::f() 的几乎整个代码,只是为了依赖参数的几行。我也不想调用函数来代替之前的#ifdef。常见的解决方案是什么?


如果你想避免重复函数逻辑f你可以使用模板方法模式 http://en.wikipedia.org/wiki/Template_method_pattern(不,不是那种template http://www.cplusplus.com/doc/tutorial/templates/.

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
    }
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

模板参数、#define 和代码重复 的相关文章

随机推荐