fork(1) download
  1. #include <cstddef>
  2. #include <iostream>
  3. #include <type_traits>
  4.  
  5. namespace mpl {
  6. template<typename... Ts>
  7. struct TypeList
  8. {
  9. static constexpr std::size_t size{ sizeof... (Ts) };
  10. };
  11.  
  12. // -----
  13.  
  14. template<typename, typename>
  15. struct IndexOf {};
  16.  
  17. // IndexOf base case: found the type we're looking for.
  18. template <typename T, typename... Ts>
  19. struct IndexOf<T, TypeList<T, Ts...>>
  20. : std::integral_constant<std::size_t, 0>
  21. {
  22. };
  23.  
  24. // IndexOf recursive case: 1 + IndexOf the rest of the types.
  25. template <typename T, typename TOther, typename... Ts>
  26. struct IndexOf<T, TypeList<TOther, Ts...>>
  27. : std::integral_constant<std::size_t,
  28. 1 + IndexOf<T, TypeList<Ts...>>::value>
  29. {
  30. };
  31. } // namespace mpl
  32.  
  33. struct T1
  34. {
  35. };
  36.  
  37. struct T2
  38. {
  39. };
  40.  
  41. struct T3
  42. {
  43. };
  44.  
  45. using Types = mpl::TypeList<T1, T2, T3>;
  46.  
  47. int main() {
  48. using namespace mpl;
  49.  
  50. std::cout << "Given TypeList<T1, T2, T3>..."
  51. << "\nT1 is type #" << IndexOf<T1, Types>::value
  52. << "\nT2 is type #" << IndexOf<T2, Types>::value
  53. << "\nT3 is type #" << IndexOf<T3, Types>::value
  54.  
  55. // Breaks if uncommented.
  56. // << "\nint is type #" << IndexOf<int, Types>::value
  57.  
  58. << std::endl;
  59. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Given TypeList<T1, T2, T3>...
T1 is type #0
T2 is type #1
T3 is type #2