Created
December 17, 2015 15:53
-
-
Save nekko1119/cf9d82801b56dab67535 to your computer and use it in GitHub Desktop.
仮想関数テーブルシミュレーション
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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