模板参数,#define和代码复制 [英] template parameters, #define and code duplication

查看:138
本文介绍了模板参数,#define和代码复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多这样的代码:

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

and I'd like to replace the #defines with template parameters:

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

但是我不想重复A :: f ; 0> :: f()和A 1 :: f()仅用于依赖于参数的几行。我也不想调用函数,而不是以前的#ifdefs。什么是常见的解决方案?

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?

推荐答案

我相信你想要的是一个等同于语言。我恐怕这样的功能不存在于C ++中。

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

如果您的#ifdef语句被用来做同样的子任务不同,然后定义子功能是正确的事情要做。

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.

strong> EDIT2

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

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

这篇关于模板参数,#define和代码复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆