使用`#ifdef`或继承进行交叉编译更好吗? [英] Is it better to use `#ifdef` or inheritance for cross-compiling?

查看:93
本文介绍了使用`#ifdef`或继承进行交叉编译更好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要遵循我的关于虚拟继承和多重继承的先前问题(在跨平台方案中)-阅读一些答案后,我想到可以通过保留服务器和客户端类并替换特定于平台的类来简化模型#ifdefs(这是我本来要做的).

To follow from my previous question about virtual and multiple inheritance (in a cross platform scenario) - after reading some answers, it has occurred to me that I could simplify my model by keeping the server and client classes, and replacing the platform specific classes with #ifdefs (which is what I was going to do originally).

使用此代码会更简单吗?这意味着至少文件更少!缺点是它会创建一个丑陋的"类,并且由于在整个地方都存在#ifdefs,因此很难读取Foobar类.请注意,我们的Unix Foobar源代码永远不会传递给编译器,因此它与#ifdef具有相同的效果(因为我们还将使用#ifdef来决定要调用的平台特定类).

Will using this code be simpler? It'd mean there'd be less files at least! The downside is that it creates a somewhat "ugly" and slightly harder to read Foobar class since there's #ifdefs all over the place. Note that our Unix Foobar source code will never be passed to the compiler, so this has the same effect as #ifdef (since we'd also use #ifdef to decide what platform specific class to call).

class Foobar {
public:
  int someData;

#if WINDOWS
  void someWinFunc1();
  void someWinFunc2();
#elif UNIX
  void someUnixFunc1();
  void someUnixFunc2();
#endif

  void crossPlatformFunc();
};

class FoobarClient : public Foobar;
class FoobarServer : public Foobar;

注意:为简化示例,遗漏了一些东西(ctor等).

Note: Some stuff (ctor, etc) left out for a simpler example.

对于那些想深入了解此问题背景的人,我真的建议略读适当的邮件列表线程.在第3个帖子周围,事情开始变得有趣起来.还有一个相关的代码提交可以在这里看到有问题的真实代码.

For those who want to read more into the background of this issue, I really suggest skimming over the appropriate mailing list thread. Thing start to get interesting around the 3rd post. Also there is a related code commit with which you can see the real life code in question here.

推荐答案

最好在方法中包含操作的平台相关性质,因此类声明在各个平台之间保持相同. (即在实现中使用#ifdefs)

Preferably, contain the platform dependant nature of the operations within the methods so the class declaration remains the same across platforms. (ie, use #ifdefs in the implementations)

如果您不能执行此操作,则您的类应该是两个完全独立的类,每个平台一个.

If you can't do this, then your class ought to be two completely separate classes, one for each platform.

这篇关于使用`#ifdef`或继承进行交叉编译更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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