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

Tho*_*mas 7 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
}
Run Code Online (Sandbox Code Playgroud)

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

template < int WITH_FEATURE_X > // can be 0 or 1
struct A;
Run Code Online (Sandbox Code Playgroud)

但我不想为A <0> :: f()和A <1> :: f()几乎复制A :: f()的整个代码,只是为了依赖于参数的几行.我也不想调用函数而不是之前的#ifdefs.什么是常见的解决方案?

Ben*_*oît 1

我相信你想要的是相当于D语言中存在的“static if”命令。恐怕C++中不存在这样的功能。

请注意,如果代码的某些部分根据您请求的功能而有所不同,则这些部分不属于主函数,因为它们不是裸算法的一部分。因此,在函数中委托此类功能的选项似乎是一个不错的选择。

编辑
如果您的 #ifdef 语句用于以不同的方式执行相同的子任务,那么定义子函数是正确的做法。它将使您的代码更具可读性,而不是更少。

如果它们用于完全不同的操作,那么您的代码已经很混乱了。做点什么吧。

至于您担心可能出现的性能问题,请相信您的编译器。

EDIT2
我忘记提及代码第一部分的答案:使用以下技巧根据“功能”添加或删除成员。

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
};
Run Code Online (Sandbox Code Playgroud)