mardi 5 septembre 2017

Simulating std::forward with std::forward_as_tuple

Let's say I use std::forward_as_tuple to store the arguments of a function call in a tuple

auto args = std::forward_as_tuple(std::forward<Args>(args)...);

And then I pass this tuple by lvalue reference to a function that wants to invoke a function foo() with some of the arguments in args as determined by another std::integer_sequence. I do it with std::move() like so

template <typename TupleArgs, std::size_t... Indices>
decltype(auto) forward_to_foo(TupleArgs& args, 
                              std::index_sequence<Indices...>) {
    return foo(std::get<Indices>(std::move(args))...);
}

And this would work because the rvalue qualified version of std::get<std::tuple> return std::tuple_element_t<Index, tuple<Types...>>&& which is an identity transformation of the reference-ness of the std::tuple_element_t<Index, tuple<Types...>> because of reference collapsing with the &&, so if std::tuple_element_t<Index, tuple<Types...>> evaluates to T& the returned type would be T& && which is just T&. Similar reason for when std::tuple_element_t<Index, tuple<Types...>> returns T&& and T

Am I missing something? Are there some cases where this would fail?

Aucun commentaire:

Enregistrer un commentaire