0

I try to pass member pointer to C++11 lambda without success

pHub is the member pointer

I keep getting the following error

error C2664: 'void Timer::start(void (__cdecl *)(Timer *),int,int)': cannot convert argument 1 from 'Scheduler::start::<lambda_292d45d0b31426827abd837d93b45bff>' to 'void (__cdecl *)(Timer *)'

I want to be able to use pHub inside the function

  pTimer = new Timer(pHub->getLoop());
        pTimer->start([this](Timer *tick) {
            uv_update_time(pHub->getLoop());
            start_time = uv_now(pHub->getLoop());
            printf("Im Tick\n");
        }, 1000, 1000);
Praetorian
  • 106,671
  • 19
  • 240
  • 328
user63898
  • 29,839
  • 85
  • 272
  • 514

1 Answers1

1

The error is not from creating the lambda; it's from trying to pass the lambda to Timer::start().

Timer::start() is expecting an argument of type void (__cdecl *)(Timer *) -- that is, a plain function pointer. Because you're trying to capture some data ([this]), your lambda expression is creating a functor (a callable object).

Think about it: Timer::start()'s function pointer argument is going to get passed a single pointer (which it expects to point to an appropriate function). There's no place for any additional data (this, the address of a functor, etc.) to be passed along. (This is why callback code in C typically has a callback data argument along with a function pointer.)

More comprehensive answer: Passing lambda as function pointer

Thomas Flinkow
  • 4,845
  • 5
  • 29
  • 65