如何摆脱这里的dynamic_cast?
我正在为我的游戏制作一个简单的图形引擎。
这是接口部分:
class Texture { ... };
class DrawContext
{
virtual void set_texture(Texture* texture) = 0;
}
这是实现部分:
class GLTexture : public Texture
{
public:
...
GLuint handle;
};
void GLDrawContext::set_texture(Texture* texture)
{
// Check if it's GLTexture, otherwise do nothing.
if (GLTexture* gl_texture = dynamic_cast<GLTexture*>(texture))
{
glBindTexture(GL_TEXTURE_2D, gl_texture->handle);
}
}
这里使用dynamic_cast 有意义吗?有办法避免吗?
I'm making a simple graphics engine for my game.
This is interface part:
class Texture { ... };
class DrawContext
{
virtual void set_texture(Texture* texture) = 0;
}
This is implementation part:
class GLTexture : public Texture
{
public:
...
GLuint handle;
};
void GLDrawContext::set_texture(Texture* texture)
{
// Check if it's GLTexture, otherwise do nothing.
if (GLTexture* gl_texture = dynamic_cast<GLTexture*>(texture))
{
glBindTexture(GL_TEXTURE_2D, gl_texture->handle);
}
}
Does it make sense to use dynamic_cast here? Is there a way to avoid it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你能尝试扭转这种担忧吗?
Could you try reversing the concern?
当然,可以使用 static_cast 来代替,但如果传入一个虚假指针,您将失去一些错误处理能力。我们使用assert_cast的想法来动态调试构建和静态发布来绕过RTTI来处理这类事情。
Sure, use static_cast instead, though you will lose some error handling if you pass in a bogus pointer. We use an assert_cast idea to dynamic on debug builds and static for release to get around the RTTI for this sort of thing.
我认为避免dynamic_cast的标准方法是向Texture类添加一个虚拟方法:
然后仅在GLTexture类中重写该方法:
然后您的调用代码将如下所示:
I think the standard way to avoid a dynamic_cast would be to add a virtual method to the Texture class:
Then override the method only in your GLTexture class:
Then your calling code would look like this:
稍微不同的方法涉及修改纹理类。
A slightly different approach that involves modifying the Texture class.
作为替代方案,您可以尝试使用泛型来摆脱动态转换。泛型可以让您在编译时捕获错误(您永远无法将 DirectX 纹理传递给 GL DrawContext)。此外,动态调度不会产生任何成本,并且编译器应该能够进行内联。
As an alternative you could try using generics to get away from dynamic cast. Generics will let you catch errors at compile time (you can never pass a DirectX texture to a GL DrawContext). Additionally, there will be no cost for dynamic dispatch and the compiler should be able to do inlining.