Search code examples
c++c++17visual-studio-2022

error C2679: binary '<<': no operator found which takes a right-hand operand of type 'main::<lambda_1>' (or there is no acceptable conversion)


I am learning to write lamda expression in cpp, Below is the code Using visual studio 2022 windows

#include<iostream>
using namespace std;

int main()
{
  int k = 98;
  int l = 23;

  auto lm_add = [k,l](int i, int j) {
    return i + j;
    };

  cout << "addition using lambada : " << "cool" << lm_add << endl;

  return 0;

Wanted to return the answer for given variables.


Solution

  • This

    auto lm_add = [k,l](int i, int j) {
        return i + j;
    };
    

    Initializes lm_add with a lambda expression. Behind the scenes the compiler generates an unnamed unique type with a call operator with the specified signature, ie taking two integers, and with members for the captures (also two integers). That type has no << operator to pipe it to an outstream. It can be called:

    std::cout << lm_add(k,l);
    

    However, it captures k and l for no good reason. Perhaps you want to either capture the variables so you can call it without arguments:

    auto lm_add = [k,l]() {
        return k + l;
    };
    
    std::cout << lm_add();
    

    Or not capture them an pass the argumetns:

    auto lm_add = [](int i,int j) {
        return i + j;
    };
    
    std::cout << lm_add(k,l);