对于上下文,我正在研究 C++人工生命系统 http://github.com/taliesinb/floatworld/涉及由循环神经网络控制的代理,但细节并不重要。
我需要将代理的“大脑”和“身体”的两个对象层次结构分开。我想要各种不同的大脑和身体类型可以在运行时相互耦合。我需要这样做是为了避免由单独关注点的乘法枚举引起的组合爆炸身体如何运作 and 大脑如何运作.
例如,循环神经网络有多种拓扑和风格,具有各种不同的传递函数和输入/输出约定。然而,这些细节并不取决于代理的身体如何工作,只要感官输入可以编码成神经活动,然后解码成动作。
这是一个简单的类层次结构,说明了问题和一个潜在的解决方案:
// Classes we are going to declare
class Image2D; // fake
class Angle2D; // fake
class Brain;
class Body;
class BodyWithEyes;
class BrainWithVisualCortex;
// Brain and Body base classes know about their parallels
class Brain
{
public:
Body* base_body;
Body* body() { return base_body; }
virtual Brain* copy() { return 0; } // fake
// ...etc
};
class Body
{
public:
Brain* base_brain;
Brain* brain() { return base_brain; }
virtual Body* reproduce() { return 0; } // fake
// ...etc
};
// Now introduce two strongly coupled derived classes, with overloaded access
// methods to each-other that return the parallel derived type
class BrainWithVisualCortex : public Brain
{
public:
BodyWithEyes* body();
virtual void look_for_snakes();
virtual Angle2D* where_to_look_next() { return 0; } // fake
};
class BodyWithEyes : public Body
{
public:
BrainWithVisualCortex* brain();
virtual void swivel_eyeballs();
virtual Image2D* get_image() { return 0; } // fake
};
// Member functions of these derived classes
void BrainWithVisualCortex::look_for_snakes()
{
Image2D* image = body()->get_image();
// ... find snakes and respond
}
void BodyWithEyes::swivel_eyeballs()
{
Angle2D* next = brain()->where_to_look_next();
// ... move muscles to achieve the brain's desired gaze
}
// Sugar to allow derived parallel classes to refer to each-other
BodyWithEyes* BrainWithVisualCortex::body()
{ return dynamic_cast<BodyWithEyes*>(base_body); }
BrainWithVisualCortex* BodyWithEyes::brain()
{ return dynamic_cast<BrainWithVisualCortex*>(base_brain); }
// pretty vacuous test
int main()
{
BodyWithEyes* body = new BodyWithEyes;
BrainWithVisualCortex* brain = new BrainWithVisualCortex;
body->base_brain = brain;
brain->base_body = body;
brain->look_for_snakes();
body->swivel_eyeballs();
}
这种方法的问题在于它很笨重并且类型不是特别安全。它确实有一个好处,那就是 body() 和 Brain() 成员函数为派生类提供了一些糖来引用它们的伙伴。
有谁知道更好的方法来实现类的“并行”层次结构之间的紧密耦合?这种模式出现的频率是否足以保证有一个众所周知的通用解决方案?仔细阅读通常的资料来源并没有发现任何与这个问题相匹配的既定模式。
任何帮助表示赞赏!
我认为你所做的大致是正确的。你会想要这样的成员reproduce
但是,它是纯虚拟的,因此无法创建基类。您的类型安全问题是什么?你不想要Brain
子类和Body
子类依赖于彼此的类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)