fork download
  1. #include <string>
  2. #include <iostream>
  3. #include <type_traits>
  4.  
  5. namespace detail
  6. {
  7. template<typename T, typename = void>
  8. struct print_helper
  9. {
  10. static T print(T t) {
  11. return t;
  12. }
  13. };
  14.  
  15. template<typename T>
  16. struct print_helper<T, decltype(std::declval<T>().print(), (void)0)>
  17. {
  18. static auto print(T t) -> decltype(t.print()) {
  19. return t.print();
  20. }
  21. };
  22. }
  23.  
  24. template<typename T>
  25. auto print(T t) -> decltype(detail::print_helper<T>::print(t))
  26. {
  27. return detail::print_helper<T>::print(t);
  28. }
  29.  
  30. struct Foo
  31. {
  32. int print()
  33. {
  34. return 42;
  35. }
  36. };
  37.  
  38. struct Bar
  39. {
  40. std::string print()
  41. {
  42. return "The answer...";
  43. }
  44. };
  45.  
  46. struct Baz
  47. {
  48. int print() { return 1729; };
  49. operator int() const
  50. {
  51. return 42;
  52. }
  53. };
  54.  
  55. int main()
  56. {
  57. Foo foo;
  58. Bar bar;
  59. Baz baz;
  60.  
  61. static_assert(std::is_same<decltype(print(foo)), int>::value, "!");
  62.  
  63. std::cout << print(foo) << std::endl;
  64. std::cout << print(bar) << std::endl;
  65. std::cout << print(baz) << std::endl;
  66. std::cout << print(42) << std::endl;
  67. }
  68.  
Success #stdin #stdout 0s 2984KB
stdin
Standard input is empty
stdout
42
The answer...
1729
42