I have the following code :
#include <functional>
#include <iostream>
struct OperatorInterface{
virtual std::string operator[](std::string str) = 0;
};
class RestApi{
public:
using func_sig = std::function<void(const int, OperatorInterface*)>;
virtual void register_get(func_sig&& functor) = 0;
virtual void apply_get(const int req, OperatorInterface*) = 0;
// here we could extend further to put, delete, post etc.
};
class RestApiImpl : public RestApi{
func_sig m_get_method;
public:
void register_get(func_sig&& functor) {
m_get_method = std::move(functor);
}
void apply_get(const int req, OperatorInterface* interface){
m_get_method(req, interface);
}
};
class ASpecificJSONLibrary{
public:
std::string operator[](std::string key){
return key + "_withLambda";
}
};
class Server{
public:
ASpecificJSONLibrary* libObj; // this is a
Server(){
libObj = new ASpecificJSONLibrary();
}
void run(RestApi* api){
api->apply_get(0, new impl(*this)) ;
}
struct impl : public OperatorInterface {
public:
Server& m_server;
impl(Server& server ) : m_server(server){}
std::string operator[](std::string key) override{
return (*m_server.libObj)[key];
}
} ;
};
int main(){
RestApi* api = new RestApiImpl();
api->register_get([](int i, OperatorInterface* intf ){
std::string dummy = "dummy";
std::cout << (*intf)[dummy];
} );
Server* server= new Server();
server->run(api);
return 0;
};
The motivation and goal for this design is to hide the details for what JSON library I am using. In essence, I dont want my RestAPI implementation to know about the underlaying detail of what Json library I am using.
Currently, I basically have just added another interface to the apply_get function which then implements its own operator, accesses the json value from the specific library and returns the value as string (for now just a dummy illustration above ASpecificJSONLibrary).
My question is if there is an alternative (more performant) solution to passing an interface to the lambda function and therefore avoid having to make two virtual functions for each time the run method is executed by e.g. templating a lambda function?
The goal is to be able to use the specific json libray as part of executing the RestAPI get method, for example, use the operator[] to get the values for each key, but by avoiding having to add another virtual function.
The Server class knows at compile time which json library to use and therefore I was wondering whether this could be exploited in conjuntion with templates