Skip to content

Instantly share code, notes, and snippets.

@nurettin
Last active December 28, 2015 23:59
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 nurettin/7582511 to your computer and use it in GitHub Desktop.
Save nurettin/7582511 to your computer and use it in GitHub Desktop.
The Pwned Combinator
/*
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