Last active
December 28, 2015 23:59
-
-
Save nurettin/7582511 to your computer and use it in GitHub Desktop.
The Pwned Combinator
This file contains hidden or 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
/* | |
The Pwned Combinator is a patten which gives you the ability to store a common base for templated classes in a container | |
while not losing the ability to access the member variables and functions of the derived instance. | |
In this pattern, the base class uses polymorphism to signal usage which then triggers the callable. | |
*/ | |
struct Base | |
{ | |
virtual void use()= 0; | |
virtual ~Base(){} | |
}; | |
#include <functional> | |
template <typename T> | |
struct Derived: Base | |
{ | |
typedef std::function<void(Derived &)> Signal; | |
T data; | |
Signal signal; | |
Derived(T const &data) | |
: data(data) | |
{} | |
void use(){ signal(*this); } | |
}; | |
#include <vector> | |
#include <iostream> | |
int main() | |
{ | |
std::vector<std::reference_wrapper<Base>> objects; | |
Derived<int> d1(42); | |
Derived<std::string> d2("omg"); | |
d1.signal= [](Derived<int> &d){ std::cout<< "d1's data: "<< d.data<< '\n'; }; | |
objects.push_back(d1); | |
d2.signal= [](Derived<std::string> &d){ std::cout<< "d2's data: "<< d.data<< '\n'; }; | |
objects.push_back(d2); | |
objects[0].get().use(); | |
objects[1].get().use(); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment