Skip to content

Instantly share code, notes, and snippets.

@kestred
Created November 10, 2013 01:52
Show Gist options
  • Save kestred/7392594 to your computer and use it in GitHub Desktop.
Save kestred/7392594 to your computer and use it in GitHub Desktop.
Attempting to implement python-style decorators in C++. Not sure I like it write now.
#include <iostream>
#include <functional>
#include <unordered_map>
#include <string>
using std::placeholders::_1;
#define DCLASS(name) \
typedef std::function<void(name&)> atomic_t; \
std::unordered_map<std::string, atomic_t> m_atomics;
#define ATOMIC(name, cls, fn, fields, ...) \
void setup(cls& dclass) { \
fields \
dclass.m_atomics[name] = std::bind(&fn, _1, __VA_ARGS__); \
}
class Foo {
public:
DCLASS(Foo)
void Fizz(int a, int b);
};
ATOMIC("fizz", Foo, Foo::Fizz, int a = 2; int b = 3;, a, b)
void Foo::Fizz(int a, int b) {
std::cout << a << " " << b;
// do stuff
}
int main()
{
Foo k = Foo();
setup(k);
k.m_atomics["fizz"](k);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment