Thanks to Can I implement max(A, max(B, max(C, D))) using fold expressions? I'm aware of one working approach to use std::min in a fold expression(min2
below). However, I'm curious why the below approaches min1
and min3
are considered undefined behavior(seemingly given the warning)?
Per my understanding the expression should evaluate in both cases from left to right, constantly updating myMin
and assign the last value back to myMin
. Additionally, the final answer is also always correct on both gcc and clang.
template <typename... Args>
auto min1(const Args&... anArgs) {
constexpr size_t N = sizeof...(anArgs);
auto myMin = std::get<0>(std::tuple(anArgs...));
myMin = std::get<N-1>(std::tuple((myMin = std::min(myMin, anArgs))...));
return myMin;
}
template <typename... Args>
auto min2(const Args&... anArgs) {
return std::min({anArgs...});
}
template <typename... Args>
auto min3(const Args&... anArgs) {
auto myMin = (anArgs, ...);
myMin = ((myMin = std::min(myMin, anArgs)), ...);
return myMin;
}
The warnings are:
main.cpp: In instantiation of 'auto min1(const Args& ...) [with Args = {int, int, int}]':
main.cpp:26:30: required from here
main.cpp:8:45: warning: operation on 'myMin' may be undefined [-Wsequence-point]
8 | myMin = std::get<N-1>(std::tuple((myMin = std::min(myMin, anArgs))...));
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:8:45: warning: operation on 'myMin' may be undefined [-Wsequence-point]
main.cpp: In instantiation of 'auto min3(const Args& ...) [with Args = {int, int, int}]':
main.cpp:29:30: required from here
main.cpp:20:10: warning: left operand of comma operator has no effect [-Wunused-value]
20 | auto myMin = (anArgs, ...);
| ^~~~~
main.cpp:20:10: warning: left operand of comma operator has no effect [-Wunused-value]
main.cpp:21:11: warning: operation on 'myMin' may be undefined [-Wsequence-point]
21 | myMin = ((myMin = std::min(myMin, anArgs)), ...);
Finally, the reason I'm looking into alternate approaches(specifically min1) is because I'm trying to use a 3rd party library for which the comma operator is deprecated and I was wondering if this can still be solved using fold expressions.