jeudi 18 août 2022

Calling a function object as a function pointer

i have the below - minimal reproducable code. I am building a REST API for an embedded device, and i am trying to bind a list of functions to a map. That way i can index them and execute depending on the parameters/endpoint that is passed in/visited by the user.

EDIT: Forgot my question - oops.

How do i call the function object as a function pointer? How do i execute the function passed into the lambda? I can't figure out the syntax.

Header File

typedef std::function<void(AsyncWebServerRequest *)> route_method;
typedef std::unordered_map<std::string, route_method> route_t;
typedef std::unordered_map<std::string, route_t> route_map_t;

route_t routes;
route_map_t route_map;

CPP

std::vector<std::string> APIServer::routeHandler(std::string index, route_t route)
{
    route_map.emplace(index, route);
    std::vector<std::string> indexes;
    indexes.reserve(route.size());

    for (const auto &key : route)
    {
        indexes.push_back(key.first);
    }

    return indexes;
}

void APIServer::setupServer()
{
    routes.emplace("wifi", [&](AsyncWebServerRequest *request)
                   { setWiFi(request); });
    routeHandler("built_in", routes);
}

void APIServer::handleRequest(AsyncWebServerRequest *request)
{
    auto it_map = route_map.find(param->name().c_str());
    auto it_method = it_map->second.find(param->value().c_str());
    {
        if (it_map != route_map.end())
        {
            if (it_method != it_map->second.end())
            {
                it_method->second(request); // how do i call the function object as a function pointer?
            }
            else
            {
                // return 404
            }
         }  
}

Aucun commentaire:

Enregistrer un commentaire