c++ - How to simplify call syntax to function which accepts generic method pointer C++14 -
i'm designing message queue actor system, message queue contains std::function objects. client code add message queue has complex syntax i'd simplify. example code:
class actor { std::deque<std::function<void()>> fmessagequeue; template <class f, class ... args> void addmessage(f &&fn, args && ... args) { fmessagequeue.push_back(std::bind(std::forward<f>(fn), std::forward<args>(args)...)); } } class myactor : public actor { void behaviour1(float arg) {/*do something*/} }
to use above classes, i'd this:
int main(int argc, const char **argv) { myactor a; a.addmessage(&myactor::behaviour1, &a, 1.0f); // redundant 2nd argument &a, needed std::bind() }
ideally, i'd use following code syntax:
int main(int argc, const char **argv) { myactor a; a.addmessage(&myactor::behaviour1, 1.0f); // notice no 2nd argument &a }
i client api not require 2nd instance of 'a' (used 2nd argument std::bind()).
while searching net, managed find close i'd achieve, argument syntax reversed:
template <class m> struct behaviour; template <class c, class ... args> struct behaviour<void(c::*)(args ...)> { using m = void (c::*)(args ...); template <m mp> static void call(c *target, args && ... args) { target->fmessagequeue.push_back(std::bind(mp, target, args ...)); } }; #define msg(m) behaviour<decltype(m)>::call<m>
and example call usage be:
int main(int argc, char **argv) { myactor a; actor::msg(&myactor::behaviour1)(&a, 1.0f); }
this more legible, still not quite ideal call syntax. dont macro msg. easiest api call syntax be:
a.addmessage(&myactor::behaviour1, 1.0f);
does know how can simplify call syntax client doesn't have specify argument #2?
Comments
Post a Comment