fork download
  1. #include <functional>
  2. #include <type_traits>
  3. #include <iostream> //just form cout for demonstration
  4.  
  5. class base {
  6. int number = 42;
  7. public:
  8. void a_method(void) {
  9. std::cout << number << std::endl;
  10. }
  11. };
  12.  
  13. class derived : public base {
  14.  
  15. };
  16.  
  17. class another_class{
  18. public:
  19. void a_method(void) {
  20. std::cout << 41;
  21. }
  22. };
  23.  
  24. template <class class_type,class function_type>
  25. void bind_base_method(function_type function, base& instance) {
  26. static_assert(std::is_base_of<base,class_type>::value || std::is_same<base,class_type>::value, "class_type is not derived of base or base");
  27. static_assert(std::is_member_function_pointer<function_type>::value, "Function is not a member function");
  28.  
  29. //call like
  30. auto this_will_call_the_method = std::bind(function, instance);
  31.  
  32. this_will_call_the_method();
  33. }
  34.  
  35. int main(void)
  36. {
  37. derived foo;
  38. bind_base_method<derived>(&derived::a_method, foo);
  39.  
  40. another_class bar;
  41. //bind_base_method(&another_class::a_method, bar);//error won't work as wanted
  42.  
  43. return 0;
  44. }
  45.  
  46.  
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
42