Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <type_traits>
- namespace
- {
- template< std::size_t index, typename ...types >
- struct type_by_index
- {
- static_assert((index < sizeof...(types)), "index is too big");
- };
- template< typename first, typename ...rest >
- struct type_by_index< sizeof...(rest), first, rest... >
- {
- using type = first;
- };
- template< std::size_t index, typename first, typename ...rest >
- struct type_by_index< index, first, rest... >
- : type_by_index< index, rest... >
- {
- };
- template< std::size_t index, typename ...types >
- using type_by_index_t = typename type_by_index< index, types... >::type;
- template< typename which, typename ...where >
- struct index_by_type
- {
- static_assert((0 < sizeof...(where)), "type is not contained within parameter pack");
- };
- template< typename which, typename ...rest >
- struct index_by_type< which, which, rest... >
- : std::integral_constant< std::size_t, sizeof...(rest) >
- {
- };
- template< typename which, typename first, typename ...rest >
- struct index_by_type< which, first, rest... >
- : index_by_type< which, rest... >
- {
- };
- // adaptors
- template< std::size_t index, typename type >
- struct type_by_index_variadic;
- template< std::size_t index, template< typename ...types > class type, typename ...types >
- struct type_by_index_variadic< index, type< types... > >
- : type_by_index< index, types... >
- {
- };
- template< std::size_t index, typename type >
- using type_by_index_variadic_t = typename type_by_index_variadic< index, type >::type;
- }
- // main.cpp
- #include <iostream>
- #include <cstdlib>
- template< typename ...types >
- struct identity
- {
- };
- using Y = struct {};
- using I = identity< double, int, struct X, Y >;
- static_assert(std::is_same< type_by_index_variadic_t< 0, I >, Y >{});
- static_assert(std::is_same< type_by_index_variadic_t< 1, I >, struct X >{});
- static_assert(std::is_same< type_by_index_variadic_t< 1, I >, X >{});
- static_assert(std::is_same< type_by_index_variadic_t< 2, I >, int >{});
- static_assert(std::is_same< type_by_index_variadic_t< 3, I >, double >{});
- static_assert(std::is_same< type_by_index_variadic_t< 0, identity< void > >, void >{});
- static_assert(index_by_type< int, int, double, char >{} == 2);
- static_assert(index_by_type< int, int >{} == 0);
- int
- main()
- {
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment