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

标签 c++ templates code-duplication

我有很多这样的代码:

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

相关文章:

c++ - 为什么一个简单的程序不能立即启动

c++ - 在 C++ 中使用 ASCII 代码将输入从小写转换为大写

jquery - Rails Jquery 从另一个 js.erb 文件渲染 js.erb 部分

c++ - 查找内存分配错误

c++ - 在 linux 下,在 C++ 中使用 system() 执行命令的转义序列

c++ - SFINAE 函数根据模板类型返回正确的字符编码?

c++ - std::enable_if 有条件地编译一个成员函数

c++ - C++1 7's deduced ` auto` 非类型 `template` 参数是否可以使用显式非类型参数模式匹配模板?

perl - 如何在 Perl 中找到复制/粘贴(复制、克隆)代码?

javascript - 使用 javascript 从具有相同类的元素克隆内容