Search code examples
c++syntaxfold-expression

Why is this C++ fold expression valid?


On cppreference, I saw that there are four types of fold expressions, unary right, unary left, binary right, and binary left. What is the type of this fold expression here? I'm having a hard time understanding why it is valid.

    template <typename Res, typename... Ts>
    vector<Res> to_vector(Ts&&... ts) {
        vector<Res> vec;
        (vec.push_back(ts) ...); // *
        return vec;
    }

What is the value of "pack", "op" and "init" in line *, if any?

This example is from page 244 of Bjarne Stroustrup's A Tour of C++ book, and seems like a comma was forgotten in the example, hence my confusion.


Solution

  • The syntax is not valid. It's missing a comma (most likely a typo):

    (vec.push_back(ts), ...)
    //                ^
    

    And so it is "unary right fold":

    ( pack op ... )
    

    with op being a comma.