Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of a tuple element's type?

If I have a tuple with different element types like

std::tuple<T0, T1, T2, ...>

And how to get the index of a element type?

template<class T, class Tuple>
struct Index
{
    enum {value = ?;}
};

Thanks.

like image 298
user1899020 Avatar asked Aug 05 '13 16:08

user1899020


People also ask

How do you determine the type of tuple element?

Given a tuple, you can extract the type of the N th element in the tuple with the help of std::tuple_element_t<N, Tuple> : // example = char using example = std::tuple_element_t<1, std::tuple<int, char, float>>; The index is zero-based, so element 0 is int , element 1 is char , and element 2 is float .

Does tuple have index?

Tuple Indexing We can access elements in a tuple in the same way as we do in lists and strings. Hence, we can access elements simply by indexing and slicing. Furthermore, the indexing is simple as in lists, starting from the index zero.

How do you access values in a tuple?

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index.


2 Answers

template <class T, class Tuple>
struct Index;

template <class T, class... Types>
struct Index<T, std::tuple<T, Types...>> {
    static const std::size_t value = 0;
};

template <class T, class U, class... Types>
struct Index<T, std::tuple<U, Types...>> {
    static const std::size_t value = 1 + Index<T, std::tuple<Types...>>::value;
};

See it live at Coliru.

This implementation returns the index of the first occurrence of a given type. Asking for the index of a type that is not in the tuple results in a compile error (and a fairly ugly one at that).

like image 74
Casey Avatar answered Sep 20 '22 23:09

Casey


template< size_t I, typename T, typename Tuple_t>
constexpr size_t index_in_tuple_fn(){
    static_assert(I < std::tuple_size<Tuple_t>::value,"The element is not in the tuple");

    typedef typename std::tuple_element<I,Tuple_t>::type el;
    if constexpr(std::is_same<T,el>::value ){
        return I;
    }else{
        return index_in_tuple_fn<I+1,T,Tuple_t>();
    }
}

template<typename T, typename Tuple_t>
struct index_in_tuple{
    static constexpr size_t value = index_in_tuple_fn<0,T,Tuple_t>();
};

The example above avoids generating tons of sub tuples, which makes compilation fail (out of memory) when you call index_in_tuple for large tuples

like image 42
pierre Avatar answered Sep 19 '22 23:09

pierre