Skip to content

Instantly share code, notes, and snippets.

@nekko1119
Created December 17, 2015 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nekko1119/cf9d82801b56dab67535 to your computer and use it in GitHub Desktop.
Save nekko1119/cf9d82801b56dab67535 to your computer and use it in GitHub Desktop.
仮想関数テーブルシミュレーション
#include <iostream>
class drawable
{
struct vtable
{
void(*draw)(void*);
};
template <typename T>
struct vtable_initializer
{
static vtable vtbl;
static void draw(void* this_)
{
static_cast<T*>(this_)->draw();
}
};
void* this_;
vtable* vptr_;
public:
template <typename T>
drawable(T& value)
: this_{std::addressof(value)}, vptr_{&vtable_initializer<T>::vtbl}
{}
void draw() const
{
vptr_->draw(this_);
}
};
template <typename T>
drawable::vtable drawable::vtable_initializer<T>::vtbl = {&drawable::vtable_initializer<T>::draw};
struct X {
void draw() const
{
std::cout << "a\n";
}
};
int main()
{
X x;
drawable d = x;
d.draw();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment