I am taking a look at an Open Source repo with this file written in C++. The two functions use lambdas and callbacks, and I just want to better understand the order of operations and how they work together.
How is this block executed when WindowScenarioselectOpen(scenarioselect_callback callback)
is called?
Here is the code block:
WindowBase* WindowScenarioselectOpen(scenarioselect_callback callback)
{
return WindowScenarioselectOpen([callback](std::string_view scenario) { callback(std::string(scenario).c_str()); });
}
WindowBase* WindowScenarioselectOpen(std::function<void(std::string_view)> callback)
{
auto* window = static_cast<ScenarioSelectWindow*>(WindowBringToFrontByClass(WindowClass::ScenarioSelect));
if (window != nullptr)
{
return window;
}
int32_t screenWidth = ContextGetWidth();
int32_t screenHeight = ContextGetHeight();
ScreenCoordsXY screenPos = { (screenWidth - WW) / 2, std::max(TOP_TOOLBAR_HEIGHT + 1, (screenHeight - WH) / 2) };
window = WindowCreate<ScenarioSelectWindow>(WindowClass::ScenarioSelect, screenPos, WW, WH, 0, callback);
return window;
}
Also, scenarioselect_callback
is defined in another file as using scenarioselect_callback = void (*)(const utf8* path);
.
To my understanding, the call to the first windowscenarioselect defined a lambda that is passed into the second one. This lambda takes in a string_view scenario
, which is used to construct a string, then converted to a C string with c_str
, which is then passed into the scenarioselect_callback
definition.
My confusion is I thought we can't construct a string
from a string_view
, and another question is, can c_str
's return which is a char*
be used as a utf8*
?
I am not so interested in the second function with a longer body, I am more interested in how the arguments are set up and work in order to make the second function work.