Skip to content

Instantly share code, notes, and snippets.

@reedacartwright
Last active February 28, 2018 00:09
Show Gist options
  • Save reedacartwright/1f7876b27ee18fba68b7927786f6311c to your computer and use it in GitHub Desktop.
Save reedacartwright/1f7876b27ee18fba68b7927786f6311c to your computer and use it in GitHub Desktop.
Example of using virtual functions to dynamically construct a functor machine
// Compile with -std=c++14
#include <array>
#include <memory>
#include <iostream>
#include <algorithm>
struct A {
virtual void operator()() = 0;
std::array<int,10> data;
};
struct B: public A {
void operator()() override {
for(auto &&a : data) {
a = 1;
}
}
};
struct C: public A {
void operator()() override {
for(auto &&a : data) {
a = 2;
}
}
};
static_assert(sizeof(A) == sizeof(B), "fail 1");
static_assert(sizeof(A) == sizeof(C), "fail 2");
int main() {
// Allocate buffer and store it in a memory managing object
auto buffer = std::make_unique<char[]>(2*sizeof(A));
A* p = reinterpret_cast<A*>(buffer.get());
// Use placement new to construct a B object and a C object
new(p) B;
new(p+1) C;
// execute each functor
std::for_each(p, p+2, [](auto &obj) {
obj();
});
// output the state of data for each object
std::for_each(p, p+2, [](auto &obj) {
for(auto &&a : obj.data) {
std::cout << a << " ";
}
std::cout << "\n";
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment