fork(2) download
  1. #include <type_traits>
  2. #include <iostream>
  3.  
  4. template< class ... >
  5. struct make_void {
  6. typedef void type;
  7. };
  8.  
  9. template<class ... T>
  10. using void_t = typename make_void< T... >::type;
  11.  
  12. template<class, class = void>
  13. struct has_method1 : std::false_type
  14. {};
  15. template<class T>
  16. struct has_method1<T, void_t<decltype(&T::method1)>> :std::true_type
  17. {};
  18. template<class, class = void>
  19. struct has_method2 : std::false_type
  20. {};
  21. template<class T>
  22. struct has_method2<T, void_t<decltype(&T::method2)>> : std::true_type
  23. {};
  24.  
  25.  
  26. template <class T>
  27. typename std::enable_if<!has_method1<T>::value && !has_method2<T>::value>::type
  28. Action(T&) {
  29. std::cout << "default" << std::endl;
  30. }
  31.  
  32. template <class T>
  33. typename std::enable_if<!has_method1<T>::value && has_method2<T>::value>::type
  34. Action(T& obj) {
  35. obj.method2();
  36. std::cout << "method2" << std::endl;
  37. }
  38. template <class T>
  39. typename std::enable_if<has_method1<T>::value>::type
  40. Action(T& obj) {
  41. obj.method1();
  42. std::cout << "method1" << std::endl;
  43. }
  44.  
  45. struct Test
  46. {};
  47.  
  48. struct Test1 {
  49. void method1() {}
  50. };
  51.  
  52. struct Test2 {
  53. void method2() {}
  54. };
  55.  
  56. struct Test12 {
  57. void method1() {}
  58. void method2() {}
  59. };
  60.  
  61. int main() {
  62. Test test;
  63. Test1 test1;
  64. Test2 test2;
  65. Test12 test12;
  66.  
  67. Action(test); // default
  68. Action(test1); // method1
  69. Action(test2); // method2
  70. Action(test12); // method1
  71.  
  72. return 0;
  73. }
  74.  
Success #stdin #stdout 0s 3096KB
stdin
Standard input is empty
stdout
default
method1
method2
method1