Как избавиться от dynamic_cast здесь? - PullRequest
1 голос
/ 22 ноября 2011

Я делаю простой графический движок для своей игры.

Это интерфейсная часть:

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 здесь? Есть ли способ избежать этого?

Ответы [ 5 ]

4 голосов
/ 22 ноября 2011

Не могли бы вы попытаться изменить ситуацию?

class Texture
{
public:
    virtual void set_texture() = 0;
};

class GLTexture : public Texture
{
public:
    virtual void set_texture();
    GLuint handle;
};

void GLTexture::set_texture()
{
    glBindTexture(GL_TEXTURE_2D, handle);
}

class DrawContext 
{ 
    virtual void set_texture(Texture* texture) = 0; 
};

class GLDrawContext : public DrawContext
{
    virtual void set_texture(Texture* texture);
};

void GLDrawContext::set_texture(Texture* texture)
{
    texture->set_texture();
}
2 голосов
/ 22 ноября 2011

Конечно, используйте static_cast вместо этого, хотя вы потеряете некоторую обработку ошибок, если передадите фиктивный указатель.Мы используем идею assert_cast для динамической отладки и статической для выпуска, чтобы обойти RTTI для такого рода вещей.

1 голос
/ 22 ноября 2011

Я думаю, что стандартный способ избежать dynamic_cast - добавить виртуальный метод в класс Texture:

virtual int get_texture_handle() const {return -1;}

Затем переопределить метод только в вашем классе GLTexture:

virtual int get_texture_handle() const {return gl_texture->handle;}

Тогда ваш код вызова будет выглядеть так:

int handle = texture->get_texture_handle();
if (handle >= 0) glBindTexture(GL_TEXTURE_2D, handle);
0 голосов
/ 22 ноября 2011

В качестве альтернативы вы можете попробовать использовать дженерики, чтобы уйти от динамического приведения. Обобщения позволят вам отлавливать ошибки во время компиляции (вы никогда не сможете передать текстуру DirectX в GL DrawContext). Кроме того, динамическая диспетчеризация не требует затрат, и компилятор должен иметь возможность делать встраивание.

namespace GL_impl {

struct Texture {
    GLuint handle;
};

struct DrawContext {
    void set_texture(Texture* texture)
    {
        glBindTexture(GL_TEXTURE_2D, texture->handle);
    }
};

} // GL_impl


struct use_GL {
    typedef GL_impl::Texture Texture;
    typedef GL_impl::DrawContext DrawContext;
};

template <class use_impl>
void f()
{
    typedef typename use_impl::Texture Texture;
    typedef typename use_impl::DrawContext DrawContext;

    Texture t;
    DrawContext ctx;
    ctx.set_texture(&t);
}

void call_f_with_gl()
{
    f<use_GL>();
}
0 голосов
/ 22 ноября 2011

Немного другой подход, включающий изменение класса Texture.

class Texture 
{
    virtual void bind_texture(){} 
};
class GLTexture : public Texture 
{
    virtual void bind_texture(); 
};
void GLTexture::bind_texture()
{
    glBindTexture(GL_TEXTURE_2D, handle);
}
class DrawContext 
{ 
    virtual void set_texture(Texture* texture) = 0; 
};
class GLDrawContext : public DrawContext
{
    virtual void set_texture(Texture* texture);
};
void GLDrawContext::set_texture(Texture* texture)
{
    if( texture )
        texture->bind_texture();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...