Guest User

Untitled

a guest
Jan 16th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. template<typename Ret>
  2. struct AnyCallable
  3. {
  4. template<typename ... Args>
  5. AnyCallable(std::function<Ret(Args...)> fun) : m_any(fun) {}
  6. template<typename ... Args>
  7. Ret operator()(Args && ... args) { return std::any_cast<std::function<Ret(Args...)>>(m_any)(std::forward<Args...>(args...)); }
  8. std::any m_any;
  9. }
  10.  
  11. template<>
  12. struct AnyCallable<void>
  13. {
  14. template<typename ... Args>
  15. AnyCallable(std::function<void(Args...)> fun) : m_any(fun) {}
  16. template<typename ... Args>
  17. void operator()(Args && ... args) { std::any_cast<std::function<void(Args...)>>(m_any)(std::forward<Args...>(args...)); }
  18. std::any m_any;
  19. }
  20.  
  21. #include "ffg.h"
  22. void foo(int x, int y)
  23. {
  24. //do something
  25. }
  26.  
  27. void bar(std::string x, int y, int z)
  28. {
  29. //do something
  30. }
  31.  
  32. int main()
  33. {
  34. std::map<std::string, AnyCallable<void>> map;
  35.  
  36. map["foo"] = &foo; //store the methods in the map
  37. map["bar"] = &bar;
  38.  
  39. map["foo"](1, 2); //call them with parameters I get at runtime
  40. map["bar"]("Hello", 1, 2);
  41. }
Add Comment
Please, Sign In to add comment