fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <string>
  4.  
  5. namespace fx {
  6. template<int I> struct placeholder{};
  7. }
  8.  
  9. namespace std{
  10. template<int I>
  11. struct is_placeholder< ::fx::placeholder<I>> : std::integral_constant<int, I>{};
  12. }
  13.  
  14. namespace fx {
  15. template <size_t... Is>
  16. struct indices {};
  17.  
  18. template <size_t N, std::size_t... Is>
  19. struct build_indices : build_indices<N-1, N-1, Is...> {};
  20.  
  21. template <size_t... Is>
  22. struct build_indices<0, Is...> : indices<Is...> {};
  23.  
  24. template<std::size_t... Is, class F, class... Args>
  25. auto easy_bind(indices<Is...>, F const& f, Args&&... args)
  26. -> decltype(std::bind(f, std::forward<Args>(args)..., placeholder<Is + 1>{}...))
  27. {
  28. return std::bind(f, std::forward<Args>(args)..., placeholder<Is + 1>{}...);
  29. }
  30.  
  31. template<class R, class... FArgs, class... Args>
  32. auto easy_bind(std::function<R(FArgs...)> f, Args&&... args)
  33. -> decltype(fx::easy_bind(build_indices<sizeof...(FArgs) - sizeof...(Args)>{}, f, std::forward<Args>(args)...)) {
  34. return fx::easy_bind(build_indices<sizeof...(FArgs) - sizeof...(Args)>{}, f, std::forward<Args>(args)...);
  35. }
  36.  
  37. template<class R, class... FArgs, class... Args>
  38. auto easy_bind(R (*f)(FArgs...), Args&&... args)
  39. -> decltype(fx::easy_bind(build_indices<sizeof...(FArgs) - sizeof...(Args)>{}, f, std::forward<Args>(args)...)) {
  40. return fx::easy_bind(build_indices<sizeof...(FArgs) - sizeof...(Args)>{}, f, std::forward<Args>(args)...);
  41. }
  42.  
  43. template <typename R, typename T, typename... FArgs, typename... Args>
  44. auto easy_bind(R (T::*mf)(FArgs...), Args&&... args)
  45. -> decltype(fx::easy_bind(std::function<R(T*,FArgs...)>(mf), args...))
  46. {
  47. return fx::easy_bind(std::function<R(T*,FArgs...)>(mf), args...);
  48. }
  49.  
  50. }
  51.  
  52. //Test Case:
  53. struct SomeStruct {
  54. void function(int x, float y, std::string str) {
  55. std::cout << x << " " << y << " " << str << std::endl;
  56. }
  57. };
  58.  
  59.  
  60. int main() {
  61. auto f = fx::easy_bind(&SomeStruct::function, new SomeStruct);
  62. f(5,2.5,"test");
  63.  
  64. return 0;
  65. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
5 2.5 test