fork(2) download
  1. #include <iostream>
  2. #include <typeinfo>
  3. #include <type_traits>
  4.  
  5. using namespace std;
  6.  
  7. struct Grandma {};
  8. struct Mom : Grandma {};
  9. struct Son : Mom {};
  10. struct Grandchild : Son {};
  11.  
  12.  
  13. template<typename...Ts>
  14. struct LCA;
  15.  
  16. template<typename T1, typename T2, typename...Ts>
  17. struct LCA<T1, T2, Ts...>
  18. {
  19. using base = typename std::conditional
  20. <
  21. std::is_base_of<T1, T2>::value, T1,
  22. typename std::conditional <
  23. std::is_base_of<T2, T1>::value, T2, void
  24. >::type
  25. >::type;
  26.  
  27. using type = typename LCA<base, Ts...>::type;
  28. };
  29.  
  30. template<typename T>
  31. struct LCA<T>
  32. {
  33. using type = T;
  34. };
  35.  
  36.  
  37. int main()
  38. {
  39. LCA<Son, Grandchild, Son>::type obj1;
  40. LCA<Son, Grandchild, Mom, Son>::type obj2;
  41. LCA<Mom, Mom, Mom>::type obj3;
  42.  
  43. cout << "obj1 type = " << typeid(obj1).name() << endl;
  44. cout << "obj2 type = " << typeid(obj2).name() << endl;
  45. cout << "obj3 type = " << typeid(obj3).name() << endl;
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
obj1 type = 3Son
obj2 type = 3Mom
obj3 type = 3Mom