好的,标题很满意,我认为这可能是为什么它很难通过谷歌或本网站找到答案。这可能只是我不知道如何正确表达问题,但这里有:将重载函数匹配到其多态参数
我在SimpleOpenGLRenderer
类中有一系列方法,它们都带有一个扩展Model
类的参数。所以这个想法是,根据模型的类型,渲染器将调用知道如何渲染它的正确方法。这是建立在对问题的简化可执行例如:
#include <stdio.h>
class Model {};
class Cube : public Model {};
class Sphere : public Model {};
class Renderer
{
public:
virtual void renderModel(const Model& model) = 0;
};
class SimpleOpenGLRenderer
{
public:
void renderModel(const Cube& model)
{
printf("Render the cube.\n");
}
void renderModel(const Model& model)
{
printf("Throw an exception, my renderer does not support the model type you have provided.\n");
}
void renderModel(const Sphere& model)
{
printf("Render the sphere.\n");
}
};
int
main(int argc, char** argv)
{
Cube cube;
Model& model = cube;
SimpleOpenGLRenderer renderer;
renderer.renderModel(cube);
renderer.renderModel(model);
}
从示例的输出是:
Render the cube.
Throw an exception, my renderer does not support the model type you have provided.
它可能看起来很明显,以更丰富的C++开发者按照计划,这并不工作,但它对我来说没有意义。在运行时,我不会知道传递给渲染器的Model
的确切类型(因此试图通过重载来解决它)。从Java背景来看,我已经使用过此技术,并且在Java中,所调用的方法将与参数的类型运行时最匹配。在C++中,它似乎与引用的编译时类型相匹配,即使该引用可能最终成为某个子类 - 在我看来 - 更好地匹配另一个函数。
直到现在我已经采取这种运行时类型匹配为理所当然。它在C++中是不是存在,还是我以错误的方式去做?我应该在C++中做不同的事情来实现它吗?
谢谢,
Gary。
谢谢。我以前没有使用过这种模式。我猜这在Java中可能不常见。我做了一些测试,我想我可能会回到'dynamic_cast'解决方案。我希望有更优雅的东西,但双派/访客模式似乎引入了我不太喜欢的各种依赖和紧密耦合。 –