I need to create a reduce function similar to std::reduce , but instead of working with containers, this function should work with variational parameters.
This is what I have:
template <typename F, typename T> constexpr decltype(auto) reduce(F&&, T &&t) { return std::forward<T>(t); } template <typename F, typename T1, typename T2, typename... Args> constexpr decltype(auto) reduce(F&& f, T1&& t1, T2&& t2, Args&&... args) { return reduce( std::forward<F>(f), std::forward<F>(f)(std::forward<T1>(t1), std::forward<T2>(t2)), std::forward<Args>(args)...); }
The following works as expected:
std::vector<int> vec; decltype(auto) u = reduce([](auto &a, auto b) -> auto& { std::copy(std::begin(b), std::end(b), std::back_inserter(a)); return a; }, vec, std::set<int>{1, 2}, std::list<int>{3, 4}, std::vector<int>{5, 6}); assert(&vec == &u);
But the following does not work:
auto u = reduce([](auto a, auto b) { std::copy(std::begin(b), std::end(b), std::back_inserter(a)); return a; }, std::vector<int>{}, std::set<int>{1, 2}, std::list<int>{3, 4}, std::vector<int>{5, 6});
This is mostly emergency. To do this, I need, for example, change the first reduce definition to:
template <typename F, typename T> constexpr auto reduce(F&&, T &&t) { return t; }
But if I do, the first snippet no longer works.
The problem is with parameter passing and the return type of the reduce function, but I can find it.
How do I change reduce definitions so that both of these snippets work?