Call function overloads with unknown pointer type
因此,我有一个基类
检查冲突时,我将所有冲突都写到
现在,在检测到所有冲突之后,我遍历
1 2 3 4 | void collide(Newtonian* first, Newtonian* second); void collide(Newtonian* object, Static* obstacle); inline void collide(Static* obstacle, Newtonian* object){ collide(object, obstacle); } void collide(Static* first, Static* second); |
问题在于,我每次必须检查要处理的对象类型,并且有可能引入了更多的
如何轻松确定要调用的重载?
当前代码:
这是我的代码当前的外观。 不漂亮。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | for (pair<Collision*,Collision*> coll : collisionVector){ Colliding* first = get<0>(coll); Colliding* second = get<1>(coll); if (Newtonian* firstNewt = dynamic_cast<Newtonian*>(first)){ if (Newtonian* secNewt = dynamic_cast<Newtonian*>(second)){ collide(firstNewt, secNewt); } else if(Static* secStat = dynamic_cast<Static*>(second)){ collide(firstNewt, secStat); } } else if(Static* firstStat = dynamic_cast<Static*>(first)){ if (Newtonian* secNewt = dynamic_cast<Newtonian*>(second)){ collide(firstStat, secNewt); } else if(Static* secStat = dynamic_cast<Static*>(second)){ collide(firstStat, secStat); } } } |
我不知道是否有一个简单的C ++技巧可以为您提供帮助(您需要的是一次对两个对象进行虚拟函数解析...)。
如果您只需要处理2种具体类型(牛顿型和静态型),我将保留已有的代码。 如果要支持更多类型,则需要使代码通用,这样就不会编写N ^ 2个案例。
我将实现某种冲突处理注册,在其中注册两种具体类型以及处理它们的方法。 不过,这并不容易。