Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming std::tuple<T...> to T

So I'm given a std::tuple<T...>, and I want to create a function pointer accepting T..., currently this is what I've got;

template<typename... Arguments>
using FunctionPointer = void (*)(Arguments...);

using FunctionPtr = FunctionPointer<typename std::tuple_element<0, V>::type,
                                    typename std::tuple_element<1, V>::type,
                                    typename std::tuple_element<2, V>::type>;

However I can't seem to find a way to do this, without manually entering each and every index from 0, ..., tuple_size<V>::value. The FunctionPtr is defined in a context, where V=std::tuple<T...> (also there is already a variadic template (hence I can't just pass T... directly))

I guess I need to generate some list of indexes, and do some black magic..

like image 511
Skeen Avatar asked Dec 26 '22 08:12

Skeen


1 Answers

Here is a possible solution:

#include <tuple>

// This is what you already have...
template<typename... Arguments>
using FunctionPointer = void (*)(Arguments...);

// Some new machinery the end user does not need to no about
namespace detail
{
    template<typename>
    struct from_tuple { };

    template<typename... Ts>
    struct from_tuple<std::tuple<Ts...>>
    {
        using FunctionPtr = FunctionPointer<Ts...>;
    };
}

//=================================================================
// This is how your original alias template ends up being rewritten
//=================================================================
template<typename T>
using FunctionPtr = typename detail::from_tuple<T>::FunctionPtr;

And here is how you would use it:

// Some function to test if the alias template works correctly
void foo(int, double, bool) { }

int main()
{
    // Given a tuple type...
    using my_tuple = std::tuple<int, double, bool>;

    // Retrieve the associated function pointer type...
    using my_fxn_ptr = FunctionPtr<my_tuple>; // <== This should be what you want

    // And verify the function pointer type is correct!
    my_fxn_ptr ptr = &foo;
}
like image 112
Andy Prowl Avatar answered Jan 08 '23 06:01

Andy Prowl