samedi 5 novembre 2022

Getting the first element of a tuple matching a certain type

I want go get the first element of a tuple which matches a given type. I think this would be more convenient and readable than the indexed get<I>( t ). My first approach is this code:

#include <iostream>
#include <tuple>
#include <type_traits>

using namespace std;

template<typename Extract, typename ... Types, size_t I>
Extract &tget( tuple<Types ...> &tpl, integral_constant<size_t, I> = integral_constant<size_t, 0>() )
{
    
    if constexpr( is_same_v<remove_cvref_t<invoke_result_t<get<Exctract>, tuple<Types ...> &, integral_constant<size_t, I>>>, Extract> )
        return get<I>( tpl );
    else
        return tget<Extract>( tpl, integral_constant<I + 1>() );
}

int main()
{
    tuple<int, float> tif;
    tget<float>( tif );
}

The compiler complains that it couldn't find a proper instance of tget, i.e. no matching overload is found.

Aucun commentaire:

Enregistrer un commentaire