Home > Enterprise >  C syntax, is this a lambda
C syntax, is this a lambda

Time:04-20

I'm building a test automation solution for a test process. I ran into a link, but my C competency isn't that great. Could someone please explain the syntax below?

void read_loop(bp::async_pipe& p, mutable_buffer buf) {
    p.async_read_some(buf, [&p,buf](std::error_code ec, size_t n) {
        std::cout << "Received " << n << " bytes (" << ec.message() << "): '";
        std::cout.write(boost::asio::buffer_cast<char const*>(buf), n) << "'" << std::endl;
        if (!ec) read_loop(p, buf);
    });
}

How to retrieve program output as soon as it printed?

My solution needs to orchestrate binaries, that monitor data traffic. There are two main programs. One manages other programs, call it B. Program A just stores all data. The testing process should inspect the outputs and match some keywords. If matched, test passes. The high level solution should do I/O to all programs--manipulating states, and matching 'outputs'.

CodePudding user response:

What a lambda looks like:

// This is the basics of a lambda expression.

[ /* Optional Capture Variables */ ]( /*Optional Parameters */ ) {
    /* Optional Code */
}

So the simplest lambda is:

[](){}

What are the different parts:

Capture Variables:   Variables from the current visible scope
                     that can be used by the lambda.
Parameters:          Just like a normal function, these are parameters
                     that are passed to the parameter when it is invoked.
Code:                This is the code that is executed and uses the
                     above mentioned variables when the lambda is invoked.

I think it is useful to consider what is likely (not specified) going on behind the senes. A Lamda is just syntactic sugar for a functor (a callabale object).

  int main()
  {
       int data = 12;
       // define the lambda.
       auto lambda = [&data](int val){
           std::cout << "Lambda: " << (val   data) << "\n";
       };

       lambda(2); // activate the lambda.
  }

This is semantically equivalent to the following:

  class CompilerGeneratedClassNameLambda
  {
      int& data;
      public:
          CompilerGeneratedClassNameLambda(int& data)
              : data(data)
          {}
          void operator()(int val) const {
              std::cout << "Lambda: " << (val   data) << "\n";
          }
  };
  int main()
  {
       int data = 12;
       CompilerGeneratedClassNameLambda lambda(data);

       lambda(2); // activate the lambda.
  }

In your code. This part is the lambda:

[&p,buf](std::error_code ec, size_t n) {
        std::cout << "Received " << n << " bytes (" << ec.message() << "): '";
        std::cout.write(boost::asio::buffer_cast<char const*>(buf), n) << "'" << std::endl;
        if (!ec) read_loop(p, buf);
    }
  • Related