C++ Best approach for reduction operation

Viewed 55

Consider a course of operation that takes in any number of parameters whose size is KNOWN at compile time. If it's one, return directly; if it is more than one, apply a user provided reduction operator that is capable of returning a type that is different than any one of the parameters'.

So the question is: What's the best approach?

I can think of two as below:

  • constexpr if checks on the size of the parameters. If it's one, pass thru; If it's two, apply reduction op.
  • Have a generic perfect pass-thru function that serves as the default reduction op.

Illustrative code as below: https://godbolt.org/z/o19sc5q19

#include <tuple>

// Approach 1
template <typename F, typename... Args>
auto ApproachOne(std::tuple<Args...> intermediate_results, F&& reduction_op) {
    if constexpr (sizeof...(Args) == 1) {
        return std::get<0>(intermediate_results);
    } else {
        return std::apply(reduction_op, intermediate_results);
    }
}

// Approach 2
template <typename F = decltype([]<typename T>(T&& t) {
              return std::forward<T>(t);
          }),
          typename... Args>
auto ApproachTwo(std::tuple<Args...> intermediate_results,
                 F reduction_op = F{}) {
    return std::apply(reduction_op, intermediate_results);
}

For short example driver code provided in the link, GCC and Clang have identical assemblies on either approach with optimization on. I'm wondering for large projects will there be any differences regarding the inlining and such? Or compiler is capable of translating this routine to identical code no matter what.

0 Answers
Related