Search code examples
c++c++17fold-expression

Fold Expression in C++17


I'm reading "C++17 - The Complete Guide" book and I came across the example on page 107 and 108 regarding fold expression in C++17:

template<typename First, typename... Args>
void print(First first, const Args&... args)
{
    std::cout << first;
    auto outWithSpace = [](const auto& arg)
    {
        std::cout << " " << arg;
    };
    (..., outWithSpace(args));
    std::cout << "\n";
}

Is there any reason that the author couldn't do this as follows (without separating the first argument from the rest and apart from an extra printed space!):

template<typename... Types>
void print(Types const&... args)
{
    ([](const auto& x){ std::cout << x << " "; }(args), ...);
    std::cout << "\n";
}

Solution

  • As you have already figured out, the author could not have done as you suggest because that would leave an additional space…

    What the author could have done though, would be something like

    template<typename First, typename... Args>
    void print(First first, const Args&... args)
    {
        ((std::cout << first), ..., (std::cout << ' ' << args)) << '\n';
    }
    

    or, rather

    template <typename Arg, typename... Args>
    std::ostream& print(Arg&& arg, Args&&... args)
    {
        return ((std::cout << std::forward<Arg>(arg)), ..., (std::cout << ' ' << std::forward<Args>(args))) << '\n';
    }
    

    live example here