【问题标题】:Fold Expression in C++17C++17 中的折叠表达式
【发布时间】:2019-12-16 22:30:57
【问题描述】:

我正在阅读“C++17 - The Complete Guide”一书,我在第 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";
}

是否有任何理由作者不能这样做(没有将第一个参数与其余参数分开,并且除了额外的打印空间!):

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

【问题讨论】:

  • 我想你回答了你自己的问题?你的打印一个额外的空间。
  • @Barry,只是想确保我没有错过本书示例的要点:)
  • 简答:否。

标签: c++ c++17 fold-expression


【解决方案1】:

正如你已经知道的那样,作者不能按照你的建议去做,因为那样会留下额外的空间……

虽然作者可以做了什么,就像

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

或者说

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';
}

现场示例here

【讨论】:

    【解决方案2】:

    显然可读的写法是

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

    (与std::forward 一起品尝)。做这种废话的诱惑(如果 C++17 没有杀死 wonderful 功能,可以使用bool first)是为 C++23 计划的template for 功能的动机.

    【讨论】:

    • @Barry 我认为他的意思是bool上的算术@
    • @RichardHodges:舌头在脸颊(就像答案),是的:对于像这样的奇怪情况(和代码打高尔夫球),后增量(“这已经设置了吗?”)和减量(切换)在bool 上是有用的速记,但太晦涩了。
    【解决方案3】:

    因为我们和朋友一起玩得很开心

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

    :)

    【讨论】:

      【解决方案4】:

      不,这只是美学问题。没有更多的理由。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-21
        • 2020-01-25
        • 1970-01-01
        • 1970-01-01
        • 2018-06-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多