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.
There is no implicit conversion from a
std::string_viewto astd::string, this is true. However an explicit conversion is allowed:An attempt to summon an implicit conversion with a plain
return sv;won't work here, but an explicit construction is allowed. And does what's expected: a resultingstd::stringcontaining the same sequence as the definedstd::string_view.Nope. For starters,
c_str()returns aconst char *and not achar *.Details matter. A
const utf8 *is specified here, notutf8 *. A brief search of the C++ standard does not appear to find any mention of a type calledutf8that's defined in the C++ library.Occam's razor concludes that
utf8is just your application code'stypedeffor achar, so you really have aconst char *here, whichc_str()is more than happy to return.