Skip to content

Instantly share code, notes, and snippets.

@d5
Created February 12, 2012 13:05
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 d5/1808375 to your computer and use it in GitHub Desktop.
Save d5/1808375 to your computer and use it in GitHub Desktop.
Get the first index of type in the std::tuple<>
#include <tuple>
// ...
template<typename T, typename C, std::size_t I>
struct tuple_index_r;
template<typename H, typename ...R, typename C, std::size_t I>
struct tuple_index_r<std::tuple<H, R...>, C, I>
: public std::conditional<std::is_same<C, H>::value,
std::integral_constant<std::size_t, I>,
tuple_index_r<std::tuple<R...>, C, I+1>>::type
{};
template<typename C, std::size_t I>
struct tuple_index_r<std::tuple<>, C, I>
{};
template<typename T, typename C>
struct tuple_index_of
: public std::integral_constant<std::size_t, tuple_index_r<T, C, 0>::value> {};
/// Example
printf("%d\n", tuple_index_of<std::tuple<int, bool, float, int>, int>::value);
printf("%d\n", tuple_index_of<std::tuple<int, bool, float, int>, float>::value);
printf("%d\n", tuple_index_of<std::tuple<int, bool, float, int>, char>::value); // compile error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment