fork download
  1. #include <iostream>
  2. #include <typeinfo>
  3.  
  4. using namespace std;
  5.  
  6. template <typename T>
  7. class base {
  8. public:
  9. base (T val = T())
  10. : m_val(val)
  11. {}
  12. base (const base &other)
  13. : base(other.m_val)
  14. {}
  15. virtual void base_specific_method()
  16. {
  17. cout << __func__ << " method called: " << m_val << endl;
  18. }
  19. void each_class_has_this() {
  20. cout << __func__ << " this is boring..." << endl;
  21. }
  22. T m_val;
  23. };
  24. class other {
  25. public:
  26. void each_class_has_this() {
  27. cout << __func__ <<" this is boring..." << endl;
  28. }
  29. };
  30. class derived_i : public base <int>
  31. {
  32. public:
  33. derived_i () : base <int> (10)
  34. {}
  35. virtual void base_specific_method()
  36. {
  37. cout << __func__ <<" Hey! I'm interesting derived! And 10 == " << m_val << endl;
  38. }
  39. };
  40.  
  41. template <typename T>
  42. class has_specific
  43. {
  44. typedef char one;
  45. typedef long two;
  46.  
  47. template <typename C> static one test( typeof(&C::base_specific_method) ) ;
  48. template <typename C> static two test(...);
  49.  
  50. public:
  51. enum { value = sizeof(test<T>(0)) == sizeof(char) };
  52. };
  53.  
  54. template <typename T>
  55. class caller {
  56. public:
  57. caller (T val = T())
  58. : m_val(val)
  59. {}
  60. void call() {
  61. p_call(m_val);
  62. }
  63. private:
  64. template <typename T1=T>
  65. typename enable_if<!has_specific<T1>::value,void>::type
  66. p_call (T1 &val)
  67. {
  68. val.each_class_has_this();
  69. }
  70. template <typename T1=T>
  71. typename enable_if<has_specific<T1>::value,void>::type
  72. p_call (T1 &val)
  73. {
  74. val.base_specific_method();
  75. }
  76. private:
  77. T m_val;
  78. };
  79.  
  80. int main ()
  81. {
  82. caller<other> c1;
  83. caller<base<double> > c2;
  84. caller<derived_i > c3;
  85.  
  86. c1.call();
  87. c2.call();
  88. c3.call();
  89. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
each_class_has_this this is boring...
base_specific_method method called: 0
base_specific_method Hey! I'm interesting derived! And 10 == 10