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. operator int() const
  38. {
  39. return 32;
  40. }
  41. };
  42.  
  43. struct Bar
  44. {
  45. std::string print()
  46. {
  47. return "The answer...";
  48. }
  49.  
  50. operator int() const
  51. {
  52. return (int)Foo();
  53. }
  54. };
  55.  
  56. struct Baz
  57. {
  58. operator std::string() const
  59. {
  60. return std::string("The answer...");
  61. }
  62. };
  63.  
  64. int main()
  65. {
  66. std::cout << print(Foo()) << std::endl;
  67. std::cout << print(Bar()) << std::endl;
  68. std::cout << print(42) << std::endl;
  69. std::cout << print((int)Foo()) << std::endl;
  70. std::cout << print("The answer...") << std::endl;
  71. std::cout << print(std::string("The answer...")) << std::endl;
  72. std::cout << print((int)Bar()) << std::endl;
  73. std::cout << print((std::string)Baz()) << std::endl;
  74. }
  75.  
Success #stdin #stdout 0s 3028KB
stdin
Standard input is empty
stdout
42
The answer...
42
32
The answer...
The answer...
32
The answer...