#How to format a capturing lambda (within an object method) for callback. Non-capture version works.

11 messages · Page 1 of 1 (latest)

chilly pollen
#
// This works fine
auto shiftIndexCallback {
  [](ImGuiInputTextCallbackData *data) -> int 
  { ... }
}

// This will not compile
int a,b,c;
auto shiftIndexCapturingCallback {
  [a,b,c](ImGuiInputTextCallbackData *data) -> int 
  { ... }
}

// Being used as parameter to specify a callback
if (ImGui::InputTextWithHint("##library_search_str", hint.c_str(), library_search_str, sizeof(library_search_str)
  , ImGuiInputTextFlags_CallbackEdit
  , shiftIndexCapturingCallback
  )
  ) { ... }

The compile error I get (linux g++);

error: cannot convert ‘Foo::bar()::<lambda(ImGuiInputTextCallbackData*)>’ to ‘ImGuiInputTextCallback’ {aka ‘int (*)(ImGuiInputTextCallbackData*)’}
 1205 |    , shiftIndexCapturingCallback
      |       ^~~~~~~~~~~~~~~~~~
      |     |
      |     BoardView::MainMenu()::<lambda(ImGuiInputTextCallbackData*)>

I'm presuming I need to use something like std::function perhaps ?

analog cedarBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

swift jay
#

A capturing lambda cannot be converted into a plain function pointer

#

You can try passing what you want to capture into the data parameter of the callback if possible

chilly pollen
#

Previously I've used globals to get around it, was hoping to avoid, but I appreciate that you've given back an answer I can work with

#

( *clarification: I used an actual function [ not method ] + globals )

coarse acorn
#
template <std::callable/*concept*/ F>
void templatedFunc(F f){
   f(); // ok with functions, captured lambdas and std::function
}
                         // everything convertable to function container with this signature is ok
void stdfunctionFunc(std::functional<void()> stdf){
   stdf();
}
       // receive only function, NOT stdfunction or lambda
void rawptrFunc(void(*rawfunc)()){
    (*rawfunc)(); // dereference address and 'call' on it
}

// and here is interesting part
// lambdas can decay to raw functions pointers
// code below is valid
#

;compile

void(*f)() = []()->void{};
(*f)();
thorn martenBOT
#
Compilation successful
coarse acorn
#

but only, and only if lambda have no any member, but overridden operator()

#

if you not understand this see what lambdas compiles to, they are classes, and you replace any lambda with your own class