简体   繁体   English

C++17 中的折叠表达式

[英]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:我正在阅读“C++17 - 完整指南”一书,我在第 107 页和第 108 页上遇到了有关 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";
}

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现场示例在这里

Plainly the readable way to write this is显然,写这个的可读方式是

template<typename... Types>
void print(Types const&... args)
{
    std::size_t n = 0;
    (std::cout << " " + !n++ << args), ...);
    std::cout << '\n';
}

(with std::forward to taste). (使用std::forward品尝)。 The temptation to do this sort of nonsense (which could use bool first if C++17 hadn't killed that wonderful feature) is the motivation for the template for feature planned for C++23.做这种胡说八道的诱惑(如果 C++17 没有杀死那个美妙的特性,可以bool first使用bool first )是为 C++23 计划的特性template for的动机。

Since we're having fun times with friends因为我们和朋友一起玩得很开心

template<typename First, typename... Args>`
void print(First&& first, Args&&... args)
{
    auto emit = [](auto&&...x) { ((std::cout << x), ...); };

    (emit(first), ..., emit(' ', args)), emit('\n');
}

:) :)

No, it's just a question of aesthetics.不,这只是审美问题。 No more reason.没有更多的理由了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM