2

I was looking through this tuple for_each() implementation a few months ago and was wondering if it is possible to implement a version that collects the return values of invoking the functions into a tuple as a result?

The reason I want to do this in my code base I have the following function which takes an input a variadic list of shapes, and returns a tuple of values.

template <typename... T, typename... R>
static constexpr auto map_to_opengl(T &&... shapes)
{
  return std::make_tuple(shape_mapper::map_to_array_floats(shapes)...);
}

Well, I'd like to change my function signature to accept a tuple of shapes, and return the result of invoking the function on each shape (this should be semantically equivalent to the code above). If I can do this, I can keep my code more DRY, which is important to me.

template <typename... T, typename... R>
static constexpr auto map_to_opengl(std::tuple<T...> &&shapes)
{
  return tuple_foreach(shapes, &shape_mapper::map_to_array_floats);
}

However the implementation of tuple_foreach doesn't allow any values to be collected. Is it possible to write such a function? If it exists in Hana, I missed it :(

I guess you wouldn't call this algorithm for_each, but maybe accumulate? I'm not sure here.

4
  • You could combine your existing code with the new std::apply?
    – Kerrek SB
    Dec 17, 2016 at 14:43
  • Perhaps, but I'm unsure how to "collect" the values into a tuple if I were to call apply on each function, since each function is called one by one, I have no idea where I would put the intermediate return values.
    – Short
    Dec 17, 2016 at 14:46
  • Terminology-wise, FP languages would call this a 'map', C++ would call it a 'transform'.
    – ildjarn
    Dec 17, 2016 at 18:15
  • 1
    Indeed, you're looking for hana::transform. Dec 17, 2016 at 21:38

3 Answers 3

4

Doing it with std::apply would be something along these lines:

template<typename T, typename F>
constexpr auto map_tuple_elements(T&& tup, F f) {
    return std::apply([&f](auto&&... args){
               return std::make_tuple(f(decltype(args)(args))...);    
           }, std::forward<T>(tup));
}
3

Nothing was added to the standard library in C++17 that would particularly help here (that I can think of); here's the usual C++14 approach (using pack expansion) as a standalone algorithm:

namespace detail {
    template<typename T, typename F, std::size_t... Is>
    constexpr auto map_tuple_elements(T&& tup, F& f, std::index_sequence<Is...>) {
        return std::make_tuple(f(std::get<Is>(std::forward<T>(tup)))...);
    }
}

template<typename T, typename F, std::size_t TupSize = std::tuple_size_v<std::decay_t<T>>>
constexpr auto map_tuple_elements(T&& tup, F f) {
    return detail::map_tuple_elements(
        std::forward<T>(tup), f,
        std::make_index_sequence<TupSize>{}
    );
}

Online Demo

4
  • That is an impressively elegant solution, my friend. And the demo with examples makes this answer legendary. Thank you!! You mention "usual approach", I'd really like to learn more about that. Do you have any sources I can learn more about the "usual approach"?
    – Short
    Dec 17, 2016 at 18:37
  • @Short : I recommend reading up on std::integer_sequence and friends, and reading through some highly-voted answers that make use of them (std::index_sequence is probably the symbol to search for).
    – ildjarn
    Dec 17, 2016 at 18:47
  • nice solution! @ildjarn why std::decay is needed here for tuple_size?
    – fen
    Feb 8, 2022 at 7:39
  • @fen : As T&& is a forwarding reference, T will be tuple<...>& or tuple<...> const& when an lvalue is passed in; but std::tuple_size is only specialized for tuple<...>, so we must strip off the reference and possible const. Prior to C++20's addition of std::remove_cvref_t, using decay_t was the easy (if overkill) solution.
    – ildjarn
    Feb 8, 2022 at 12:56
0

The following main() constructs a tuple, applies a function to each value in the tuple, and produces another tuple. You can trivially wrap the whole thing into a function of its own.

This solution uses a few templates that are new to C++17, but they all can be trivially reimplemented for C++14, if necessary:

#include <utility>
#include <tuple>
#include <iostream>

// The function

int square(int n)
{
    return n * 2;
}

// The helper class for unpacking a tuple into a parameter pack,
// invoking square(), then packing the result back into a tuple.

template<typename tuple, typename index_sequence> class apply_square;

template<typename tuple,
     size_t... sequence>
class apply_square<tuple, std::index_sequence<sequence...>> {

public:

    template<typename tuple_arg>
    static auto do_apply_square(tuple_arg &&tupple)
    {
        return std::make_tuple(square(std::get<sequence>(tupple))...);
    }
};

int main()
{
    // Create a sample tuple

    auto f=std::make_tuple(1, 2);

    // Invoke appropriately-specialized do_apply_square() against
    // the tuple.

    typedef std::make_index_sequence<std::tuple_size<decltype(f)>
                     ::value> tuple_indexes;

    auto f_squared=apply_square<decltype(f), tuple_indexes>
        ::do_apply_square(f);

    // f_squared should now be another tuple. Let's see:

    int &first=std::get<0>(f_squared);
    int &second=std::get<1>(f_squared);

    std::cout << first << ' ' << second << std::endl;
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.