Skip to content

Instantly share code, notes, and snippets.

@picanumber
Last active July 10, 2020 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save picanumber/788ac0163f74c1df59dcf579bedaebd0 to your computer and use it in GitHub Desktop.
Save picanumber/788ac0163f74c1df59dcf579bedaebd0 to your computer and use it in GitHub Desktop.
In place method to find the index of a type in a tuple
template <class T, std::size_t I, class Tuple> // 1
constexpr bool match_v = std::is_same_v<T, std::tuple_element_t<I, Tuple>>;
template <class T, class Tuple, // 2
class Idxs = std::make_index_sequence<std::tuple_size_v<Tuple>>>
struct type_index;
template <class T, template <class...> class Tuple, class... Args, // 3
std::size_t... Is>
struct type_index<T, Tuple<Args...>, std::index_sequence<Is...>>
: std::integral_constant<std::size_t,
((Is * match_v<T, Is, Tuple<Args...>>) + ... + 0)> {
static_assert(1 == (match_v<T, Is, Tuple<Args...>> + ... + 0),
"T doesn't appear once in Tuple");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment