0

I am trying for_each, and realized that a lambda is assignable to bool.

    #include<vector>
    #include<iostream>
    #include<algorithm>

    int main()
    {
        std::vector<int> v{1,2,3,4,5};
        auto l = [](int i) -> void
        {
           std::cout<<i<<'\n';
        };
        std::cout << "the sum is " <<std::boolalpha<<std::for_each(v.begin(), v.end(),  l ) << "\n";

        bool b = l;
        std::cout<<b<<'\n';

    }

We know that a lambda without any capture can be treated like a C function. But not very sure about boolean conversion.

Once we reference capture, boolean conversion stops.

    auto l = [&](int i) -> void
    {
       std::cout<<a<<i<<'\n';
       a+=i;
    };
    bool b = l; //Does not compile.

So, what is the reason for boolean conversion??

g-217
  • 2,069
  • 18
  • 33

0 Answers0