Search code examples
c++tuplesvariadic

Create tuple from result of functions in callable variadic tuple


I'm trying to write the following: I have as input a tuple containing N functions. All of those functions can have different return type but only take 1 argument of the same type. I would like to put in a tuple the result of calling each function to a given parameter.

template <typename AttributeType, typename ...Functions>
auto f(std::tuple<Functions...> &tupleOfFunctions, const AttributeType &attr)
{
  return std::make_tuple(std::get<0>(tupleOfFunctions)(attr), std::get<1>(tupleOfFunctions)(attr), …, std::get<N>(tupleOfFunctions)(attr));
}

Solution

  • There you go:

    template <typename AttributeType, typename ...Functions>
    auto f(std::tuple<Functions...> &tupleOfFunctions, const AttributeType &attr)
    {
        return std::apply(
            [&](auto &... f) { return std::tuple{f(attr)...}; },
            tupleOfFunctions
        );
    }
    

    Live demo

    This can be tweaked to handle reference-returning functions transparently as well:

    template <typename AttributeType, typename ...Functions>
    auto f(std::tuple<Functions...> &tupleOfFunctions, const AttributeType &attr)
    {
        return std::apply(
            [&](auto &... f) { return std::tuple<decltype(f(attr))...>{f(attr)...}; },
            //                                  ^^^^^^^^^^^^^^^^^^^^^^
            tupleOfFunctions
        );
    }