title: Passing Lambda function without std::function with capture [this]
body: <p>I'm using the 'PacketSerial' library from Github in an Arduino program. In the examples provided with the library, everything is in loop() or setup(). I would like to move all that to the instance 'arDriver', but run into some trouble..</p>
  
  <p>I initialize it like this, which works fine (just like the examples provided);</p>
  
  <pre class="lang-cpp prettyprint-override"><code>//in app.ino
  void setup()
  {
    arDriver.setup();  //&lt;- I want to move the 2 functions below in here
    arDriver.myPacketSerial.begin(115200);
    arDriver.myPacketSerial.setPacketHandler([](const uint8_t* buffer, size_t size) 
      {
      arDriver.communicationCOBS(arDriver.myPacketSerial, buffer, size);
      });
  }
  
  //in ArduinoDriver.cpp
  void ArduinoDriver::communicationCOBS(const PacketSerial&amp; sender, const uint8_t* buffer, size_t size)
  { ... }
  
  //in PacketSerial.h
  typedef void (*PacketHandlerFunction)(const uint8_t* buffer, size_t size);
  void setPacketHandler(PacketHandlerFunction onPacketFunction)
  { ... }
  
  
  </code></pre>
  
  <p>When I move the 2 PacketSerial functions into arDriver::setup(), I get the following;
  (after solving an error that I need to capture [this])</p>
  
  <pre class="lang-cpp prettyprint-override"><code>void ArduinoDriver::setup()
  {
    ...
    myPacketSerial.begin(115200);
    myPacketSerial.setPacketHandler([this](const uint8_t* buffer, size_t size)
      {
          communicationCOBS(myPacketSerial, buffer, size);
      });
  }
  </code></pre>
  
  <p>Now I get following error which I can't solve;</p>
  
  <hr>
  
  <p>Error (active)  E0304   no instance of overloaded function "PacketSerial_::setPacketHandler [with EncoderType=COBS, PacketMarker=(uint8_t)'\000', ReceiveBufferSize=256U]" matches the argument list
  argument types are: (lambda []void (const uint8_t *buffer, size_t size) -> void)
  object type is: PacketSerial</p>
  
  <hr>
  
  <p>I found several posts and questions about similar problems, but lack the skill or knowledge to implement these in my particular application.
  Below is what I think is the most promising, but so far, I couldn't make it work..
  I prefer not to use a solution based on std::function</p>
  
  <pre class="lang-cpp prettyprint-override"><code>// from: https://bannalia.blogspot.com/2016/07/passing-capturing-c-lambda-functions-as.html
  
  void do_something(void(*callback)(void*),void* callback_arg)
  {
    ...
    callback(callback_arg);
  }
  
  int num_callbacks=0;
  ...
  auto callback=[&amp;](){
    std::cout&lt;&lt;"callback called "&lt;&lt;++num_callbacks&lt;&lt;" times \n";
  };
  auto thunk=[](void* arg){ // note thunk is captureless
    (*static_cast&lt;decltype(callback)*&gt;(arg))();
  };
  do_something(thunk,&amp;callback);
  
  output: callback called 1 times
  
  </code></pre>