Last active
October 15, 2021 19:08
-
-
Save kuujoo/655c05cebe40f43c29a8ed50315c91c5 to your computer and use it in GitHub Desktop.
C# Style actions in C++
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
/** | |
pxl::Action<int, int, bool> a; | |
a += [](int p0, int p1, bool p3) | |
{ | |
}; | |
auto id = a.bind([](int p0, int p1, bool p3) | |
{ | |
}); | |
a.invoke(1, 2, false); | |
a.unbind(id); | |
a.invoke(1, 2, false); | |
**/ | |
namespace pxl | |
{ | |
using ActionBindId = pxl::i64; | |
template<typename... Args> | |
class Action | |
{ | |
public: | |
Action() : id(0) | |
{ | |
} | |
Action& operator+=(Func<Args...> func) | |
{ | |
bind(func); | |
return *this; | |
} | |
void invoke(Args... args) | |
{ | |
for (auto b : funcs) | |
{ | |
b.func(args...); | |
} | |
} | |
ActionBindId bind(Func<Args...> func) | |
{ | |
funcs.push_back(Binder(id, func)); | |
return id++; | |
} | |
void unbind(ActionBindId removeId) | |
{ | |
funcs.erase(std::remove_if(funcs.begin(), funcs.end(), [removeId](const Binder& b) | |
{ | |
return b.id == removeId; | |
}), funcs.end()); | |
} | |
void clear() | |
{ | |
funcs.clear(); | |
} | |
private: | |
ActionBindId id; | |
struct Binder | |
{ | |
Binder(ActionBindId id, Func<Args...> func) : id(id), func(func) {} | |
ActionBindId id; | |
Func<Args...> func; | |
}; | |
pxl::Vector<Binder> funcs; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment