2

In c++17 we can easily get the cumulative product of a parameter pack like this:

template<typename... Xs> constexpr std::array<int, sizeof...(Xs)+1> cumulative_product(int x0, Xs... xs) {
    return {x0, x0 *= xs ...};
}

constexpr auto cp = cumulative_product(1,2,3,4); // -> 1, 2, 6, 24

Is there a similarly elegant way to get the product of the reverse-ordered arguments -> [4, 12, 24, 24]?

NB: in the original question I had a wrong expected result (24,6,2,1) + imprecise wording of the question. So reversing the output array is not an option here.

Given the same ordering of the input arguments, of course.

I've tried and played around with fold expressions, but it blows up the code size real quick as I couldn't find a way of doing it in the return statement directly.

NutCracker
  • 11,485
  • 4
  • 44
  • 68
florestan
  • 4,405
  • 2
  • 14
  • 28
  • 2
    once you have the array you can reverse it, no? – 463035818_is_not_an_ai Jan 31 '20 at 11:15
  • Maybe possible with the C++20 [range library](https://en.cppreference.com/w/cpp/ranges)? Perhaps using [the reverse view](https://en.cppreference.com/w/cpp/ranges/reverse_view)? For earlier standards, you could look into the [range library](https://github.com/ericniebler/range-v3) that the C++20 ranges are based on. – Some programmer dude Jan 31 '20 at 11:17
  • Sure, but I was hoping there exists a way to do it within the return statement. – florestan Jan 31 '20 at 11:17
  • I apologize, I had the original question wrong. I need the product of the arguments in reverse order (like a right-fold). I've updated the question accordingly. – florestan Jan 31 '20 at 11:42
  • 1
    @florestan You could split that off into a separate `constexpr` function and return the result of that in your return statement. Or are you looking for something specifically without modifying the pack or using functions? – super Jan 31 '20 at 11:53
  • 1
    The duplicate has many very verbose answers. In C++14 and later, you'll want [the one by Xeo](https://stackoverflow.com/a/15908420/256138). – rubenvb Jan 31 '20 at 12:00
  • Basically the answer is no there is no *elegant* way. – rustyx Jan 31 '20 at 12:53
  • @rustyx: Yeah, after looking at the posts suggested by rubenvb (thank you very much), it seems there isn't an elegant way. I was aware that I can do it with a reverse integer sequence, but I was hoping to get it somewhat less verbose... – florestan Jan 31 '20 at 12:59
  • Reverse input, cumulative_product, then reverse result. – Jarod42 Jan 31 '20 at 13:28
  • You might do something like [that](http://coliru.stacked-crooked.com/a/d7ed13fc3e310f7b) (`constexpr` in C++20). – Jarod42 Jan 31 '20 at 13:41
  • @Jarod42, thanks. That's indeed what i ended up with. Just had to copy the possible implementation from cppreference to get a `constexpr partial_sum`. – florestan Jan 31 '20 at 14:26

0 Answers0