Skip to content

Instantly share code, notes, and snippets.

@kuujoo
Last active October 15, 2021 19:08
Show Gist options
  • Save kuujoo/655c05cebe40f43c29a8ed50315c91c5 to your computer and use it in GitHub Desktop.
Save kuujoo/655c05cebe40f43c29a8ed50315c91c5 to your computer and use it in GitHub Desktop.
C# Style actions in C++
/**
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