lcs
lcs

Reputation: 4245

Forwarding tuple arguments to a function in VS2012

I'm trying to forward tuple arguments to a function in VS2012 (update 3).

My understanding is that this is possible in C++11 using variadic templates, unfortunately, VS2012 only supports "fake" variadics.

auto Values = std::make_tuple(4, 8);
auto Add = [](int a, int b) -> int { return a + b; };

auto Result = forward_to_function(Add, Values);

I'm hoping that there is a way in VS2012 to implement the functionality shown above, but I'm not sure, is this possible without true variadics?

Upvotes: 0

Views: 378

Answers (2)

Felix Glas
Felix Glas

Reputation: 15524

I know you're looking for a VS2012 compatible answer, but I'll post this solution anyway in case that you happen to be able to upgrade your compiler for some C++14 support.

If you find a hairy C++03/C++11 workaround, then you can always compare it to this C++14 code :)

It's possible to expand the tuple's arguments and pass them to the specified function using a C++14 std::integer_sequence.

template <typename Func, typename Tuple, std::size_t... Indices>
auto forward_to_function(Func&& f, Tuple&& t, std::index_sequence<Indices...>) {
    return f(std::get<Indices>(std::forward<Tuple>(t))...);
}

template <typename Func, typename Tuple>
auto forward_to_function(Func&& f, Tuple&& t) {
    constexpr auto n = std::tuple_size<std::remove_reference_t<Tuple>>::value;
    return forward_to_function(std::forward<Func>(f),
           std::forward<Tuple>(t),
           std::make_index_sequence<n>{});
}

Live example

Upvotes: 1

JDługosz
JDługosz

Reputation: 5642

I saw mention of just such an "exploder" in a Channel 9 video. I think it was the most recent "Going Native" Someone (Andrei?) was reported as having a full general solution, but it was not presented. There were less complete workable solutions talked about.

If you can wait, the current VS preview compiler has true variadics.

Look how Boost does it: implement a whole bunch of args, with a special flag type as a default argument that indicates it is missing.

Normally, for a function (not a class) I would overload it. Overloading templated functions is just fine, too: the arguments to forward_to_function must be expanded out so it can match each parameter type, so you were doing that anyway. Only instead of "..." you write some fixed number of params. Overload it with another definition that has a different number, for as many as are actually needed by the program.

—John

Upvotes: 1

Related Questions