Advertisement
Guest User

Untitled

a guest
Mar 27th, 2015
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. struct foo1;
  4. struct foo2 { typedef int bar; };
  5.  
  6. template <typename T>
  7. class has_bar
  8. {
  9. typedef char yes;
  10. typedef long no;
  11.  
  12. template <typename C> static yes check( decltype(&C::bar) ) ;
  13. template <typename C> static no check(...);
  14. public:
  15. enum { value = sizeof(check<T>(0)) == sizeof(yes) };
  16. };
  17.  
  18. int main()
  19. {
  20. std::cout << has_bar<foo1>::value << std::endl;
  21. std::cout << has_bar<foo2>::value << std::endl;
  22. return 0;
  23. }
  24.  
  25. #include <iostream>
  26.  
  27. struct foo1;
  28. struct foo2 { typedef int bar; };
  29.  
  30. template <typename T, typename U = void>
  31. struct target
  32. {
  33. target()
  34. {
  35. std::cout << "default target" << std::endl;
  36. }
  37. };
  38.  
  39. template<typename T>
  40. struct target<T, typename T::bar>
  41. {
  42. target()
  43. {
  44. std::cout << "specialized target" << std::endl;
  45. }
  46. };
  47.  
  48. int main()
  49. {
  50. target<foo1>();
  51. target<foo2>();
  52. return 0;
  53. }
  54.  
  55. template <typename C> static yes check( decltype(&C::bar) ) ;
  56.  
  57. template <typename C> static yes check( typename C::bar* ) ;
  58.  
  59. // General utility: if_<Condition, Then, Else>::type
  60. // Selects 'Then' or 'Else' type based on the value of
  61. // the 'Condition'
  62. template <bool Condition, typename Then, typename Else = void>
  63. struct if_ {
  64. typedef Then type;
  65. };
  66. template <typename Then, typename Else>
  67. struct if_<false, Then, Else > {
  68. typedef Else type;
  69. };
  70.  
  71. template <typename T, typename _ = void>
  72. struct target {
  73. // generic implementation
  74. };
  75.  
  76. template <typename T>
  77. struct target<T, typename if_<false,typename T::bar>::type> {
  78. // specialization for types holding a nested type `T::bar`
  79. };
  80.  
  81. template<class T>
  82. struct Void {
  83. typedef void type;
  84. };
  85.  
  86. template<class T, class U = void>
  87. struct has_bar {
  88. enum { value = 0 };
  89. };
  90.  
  91. template<class T>
  92. struct has_bar<T, typename Void<T::bar>::type > {
  93. enum { value = 1 };
  94. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement