objectCast 横向投射

发布于 2024-09-19 13:19:07 字数 481 浏览 12 评论 0原文

我正在尝试用QT的objectCast替换代码中的所有dynamicCast。但我遇到了一些困难。这是我的对象的层次结构:

class ABase : public QObject

class IAbility; // Registered as Qt Interface
class ISize; // Registered as Qt Interface

class Derived : public ABase, public IAbility, public ISize; // Uses Q_INTERFACES

使用 objectCast 我可以将 Derived 转换为 ISize 或 IAbility。但是,在我的代码的某一点中,我想执行以下转换:Derived->ISize->IAbility。最后一次转换是我收到错误的地方。由于 IAbility 与 ISize 没有任何关系,因此这可能会导致问题。此时我可以进行动态转换,但我不想这样做。

I'm trying to replace all dynamicCasts in my code with QT's objectCast. But I've run into a bit of a snag. Here's the hierarchy of my objects:

class ABase : public QObject

class IAbility; // Registered as Qt Interface
class ISize; // Registered as Qt Interface

class Derived : public ABase, public IAbility, public ISize; // Uses Q_INTERFACES

Using objectCast I can convert a Derived to a ISize or IAbility. However, in one point of my code I want to perform the following conversion: Derived->ISize->IAbility. That last cast is where I get an error. Since IAbility does not relate to ISize in any way, that could cause a problem. I could do a dynamic cast at this point, but I'd rather not.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木落 2024-09-26 13:19:07

在我看来,您有三个选择:

  1. 通过将两个接口放入继承层次结构中来将它们相互关联,让一个接口继承另一个接口。这会让你从一个方向投射到另一个方向,但如果两者之间没有真正的关系,也会显得笨拙和不稳定。
  2. 您创建一个超级接口,其他两个接口继承自该超级接口,如果愿意的话,可以将其用作公共铸造基础。这将允许您使用超级接口以两种方式转换对象,但也会创建不必要的抽象。
  3. 您可以将 Derived 对象转换为 ISize,执行您想要的操作,然后将相同的派生引用转换为 IAbility。因此:导出-> ISize,派生 ->我的能力。

我会选择选项 3,只是因为从抽象角度来说,它是强制程度最低的解决方案。

As I see it you have three options:

  1. You relate the two interfaces to each other by putting them in an inheritance hierarchy, letting one inherit the other. This will let you cast from one to the other, in one direction, but will also be clonky and wonky if there is no real realtion between the two.
  2. You create a super interface that the two others inherit from, and use that as a common casting ground, if you will. This will let you cast the object two ways, using the super interface, but will also create an unnessecary abstraction.
  3. You cast your Derived object to an ISize, do what you want, and then cast that same derived reference to an IAbility. Hence: Derived -> ISize, Derived -> IAbility.

I would go for option 3, simply because it's the least forced solution, abstraction-wise.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文