C++ lambda 和内联嘶嘶声

C++ lambda and inlined fizzbuzz

本文关键字:嘶嘶声 lambda C++      更新时间:2023-10-16

Heoi,我看过一个C++演讲,有人做了一个lambda fizzbuzz实现。

这不是它!甚至没有接近它!我的问题是,为什么我不能使用ostream和

auto fizz = [](int& x, std::ostream& os) { x % 3 == 0 ? os << "fizz" : 0; };
auto buzz = [](int& x, std::ostream& os) { x % 5 == 0 ? os << "buzz" : 0; };

    for (int i = 0; i != 100; ++i)
    {
        fizz(i, std::cout);
        buzz(i, std::cout);
    }

我的错误消息是:

        E1776   function "std::basic_ostream<_Elem, _Traits>::basic_ostream(const std::basic_ostream<_Elem, _Traits>::_Myt &) [with _Elem=char, _Traits=std::char_traits<char>]" (declared at line 83 of "c:Program Files (x86)Microsoft Visual Studio2017CommunityVCToolsMSVC14.12.25827includeostream") cannot be referenced -- it is a deleted function    56  

你的问题很清楚。由于std::ostreamint不属于同一类型,因此向三元运算符提供不相同的类型会产生错误。为了解决这个问题,你可能希望完全避免使用 else 子句,所以你的函数看起来像这样:

auto fizz = [](int& x, std::ostream& os) { if (x % 3 == 0) os << "fizz"; };
auto buzz = [](int& x, std::ostream& os) { if (x % 5 == 0) os << "buzz"; };