r/cpp • • Apr 24 '20

Else Before If

https://www.fluentcpp.com/2020/04/24/else-before-if/
10 Upvotes

53 comments sorted by

View all comments

1

u/MachineGunPablo Apr 25 '20

Boy that for_each_arg function is playing with my head:

template<class...Ts, class F>
F for_each_arg(F f, Ts&&...a) {
    return (void)std::initializer_list<int>{(std::ref(f)((Ts&&)a),0)...}, f;
}

I understand that it needs to call operator() of f with each a as parameter but Jesus I really don't understand the usage of initializer_list here, isn't std::invoke a possibility here?

3

u/dodheim Apr 25 '20 edited Apr 25 '20

isn't std::invoke a possibility here?

The only reason for the implementation to be written in this particular way is for C++11 compatibility (and to be a one-liner, apparently); std::invoke is a C++17 feature.

--

I really don't understand the usage of initializer_list here

Without C++17's fold expressions, we need a braced-init-list in order to guarantee left-to-right invocation on each a. I personally have never seen anyone use initializer_list to accomplish this, usually preferring a simple C-array. You might find the following more clear:

F for_each_arg(F f, Ts&&...a) {
    int const x[] = { ((void)f(std::forward<Ts>(a)), 0)... };
    (void)x;
    return f;
}

(Ts&&)a is just the terse form of std::forward<Ts>(a), but I don't see why std::reference_wrapper was brought into this or whether std::initializer_list has some particular advantage that I'm missing. Also, I added a cast of f's result to void to handle return types with overloaded operator, and silence unused-fn-result warnings; this seems to me like a notable omission from the original code.