fork download
  1. #include <iostream>
  2.  
  3. struct H1{ void operator()() { std::cout << "H1" << std::endl; } };
  4. struct H2{ void operator()() { std::cout << "H2" << std::endl; } };
  5.  
  6. typedef H1 default_H;
  7. struct U2 { typedef H2 H; };
  8. struct U1 { typedef H1 H; };
  9. struct U0 {};
  10.  
  11. template < bool > struct bool_type {};
  12.  
  13. template <typename T>
  14. class has_typedef_H {
  15. typedef char no[1];
  16. typedef char yes[2];
  17.  
  18. template <typename C>
  19. static yes& test(typename C::H*);
  20.  
  21. template <typename>
  22. static no& test(...);
  23.  
  24. public:
  25. static const bool value = sizeof(yes) == sizeof(test<T>(0));
  26. };
  27.  
  28. template<typename T,
  29. typename = bool_type< true > >
  30. struct H_type
  31. {
  32. typedef default_H type;
  33. };
  34.  
  35. template<typename T>
  36. struct H_type< T, bool_type< has_typedef_H< T >::value > >
  37. {
  38. typedef typename T::H type;
  39. };
  40.  
  41. int main() {
  42.  
  43. H_type<U0>::type h0;
  44. H_type<U1>::type h1;
  45. H_type<U2>::type h2;
  46.  
  47. // Prints H1 H1 H2
  48. h0();
  49. h1();
  50. h2();
  51. return 0;
  52. }
Success #stdin #stdout 0.01s 2680KB
stdin
Standard input is empty
stdout
H1
H1
H2