fork(2) download
  1. #include <type_traits>
  2. #include <iostream>
  3.  
  4.  
  5. template <typename T, typename M, typename ...Args>
  6. auto invoke( T *object, M method, Args&&... args ) -> decltype( *method )
  7. {
  8. return ( static_cast<T*>( object )->*method )( std::forward<Args>( args )... );
  9. }
  10.  
  11. struct Foo
  12. {
  13. int triple( int val )
  14. {
  15. return val * 3;
  16. }
  17. };
  18.  
  19. int main()
  20. {
  21. Foo foo;
  22.  
  23. std::cout << invoke( &foo, &Foo::triple, 5 ); // output: 15
  24.  
  25. return 0;
  26. }
  27.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'int main()':
prog.cpp:23:48: error: no matching function for call to 'invoke(Foo*, int (Foo::*)(int), int)'
     std::cout << invoke( &foo, &Foo::triple, 5 );   // output: 15
                                                ^
prog.cpp:6:6: note: candidate: template<class T, class M, class ... Args> decltype (* method) invoke(T*, M, Args&& ...)
 auto invoke( T *object, M method, Args&&... args ) -> decltype( *method )
      ^
prog.cpp:6:6: note:   template argument deduction/substitution failed:
prog.cpp: In substitution of 'template<class T, class M, class ... Args> decltype (* method) invoke(T*, M, Args&& ...) [with T = Foo; M = int (Foo::*)(int); Args = {int}]':
prog.cpp:23:48:   required from here
prog.cpp:6:65: error: invalid use of unary '*' on pointer to member
 auto invoke( T *object, M method, Args&&... args ) -> decltype( *method )
                                                                 ^
stdout
Standard output is empty