我有很多这样的代码:
#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;
但我不想只为依赖于参数。我也不想调用函数而不是之前的#ifdefs。常见的解决方案是什么?
最佳答案
如果你想避免重复函数 f
的逻辑,你可以使用 template method pattern (不,不是那种 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
}
};
关于c++ - 模板参数、#define 和代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3615439/