在处理对象对时避免RTTI [英] Avoid RTTI when dealing with pairs of objects

查看:88
本文介绍了在处理对象对时避免RTTI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到几个关于避免RTTI的问题,但我的看起来更具体一些。下面是一个例子:

I saw a few questions about avoiding RTTI, but mine seems to be a bit more specific. Here is an example case:

struct Base {};

struct A : Base {};
struct B : Base {};
struct C : Base {};

std::vector<Base*> vec;

我想在向量中的所有可能的(无序的)对象上做一些事情具有3个元素,具有0和1,0和2,1和2)。我想要的伪代码是:

I want to do something on all possible (unordered) pairs of objects in the vector (if the vector has 3 elements, with 0 and 1, 0 and 2, 1 and 2). The pseudo-code for what I want is something like:

if e1 is A and e2 is A:
    behavior1(e1, e2)
elif e1 is A and e2 is B:
    behavior2(e1, e2)
elif ...

很多人说RTTI是不好的设计,但是这里可以避免吗?

Lots of people say that RTTI is bad design, but could it be avoided here? And is there a more efficient way than doing all these if/elif?

推荐答案

是否选择使用或避免RTTI是一个更有效的方法,更多关于常识。虽然它可能被认为是良好的设计努力避免它,偶尔你只是想做一些事情继续前进。

Whether you choose to use or avoid RTTI is really more about common sense. While it may be considered good design to strive to avoid it, occasionally you just want to get something done and move on.

如果你只有几个类类型来处理,你可以摆脱 if / else if 并且有一个简单的函数指针表。在每个类型中使用一个虚拟函数来为用于查找正确函数调用的索引添加权重:

If you only have a couple of class types to deal with, you could get rid of the if/else if and have a simple table of function pointers. Use a virtual function in each type to add weight to the index used to look up the correct function to call:

struct Base
{
    virtual int  GetWeight() const = 0;
};

struct A : Base
{
    virtual int  GetWeight() const    { return 1; }
};

struct B : Base
{
    virtual int  GetWeight() const    { return 2; }
};

struct C : Base
{
    virtual int  GetWeight() const    { return 4; }
};


static void (*MyBehaviours)( Base*, Base* )[] = { &behaviour1, &behaviour2, ... };

MyBehaviours[ e1->GetWeight() + e2->GetWeight() ]( e1, e2 );

这篇关于在处理对象对时避免RTTI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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