The way you can bind any methods(even class's member functions) to map and call it dynamically.
#include "my_function_map.h"
std::string add_str(std::string i, std::string j) {
return i + " " + j;
}
int main() {
MyFunctionMap myFunctionMap;
myFunctionMap.bindFunction("add_str", &add_str);
std::string value = std::any_cast<std::string>(myFunctionMap.getFunction("add_str")->call({ std::string("Hello"), std::string("World") }));
std::cout << value << "\n";
}
Hello World
- The
Function
class does not have any template factors. - Only
CallableFunction
andCallableClassFunction
, which inherit theFunction
class, have template factors. - The
MyFunctionMap
class has a pointer of theFunction
class as information of the map. - The
call
function of theFunction
class is declared as a virtual function. - In the
call
function, the internal binded function is called through the C++'svariadic template
andstd::apply
.
You can use this technique to your own dynamic language interpreter.
- Only C++ 17+ compiler can compile this source.
- When you call
Function::call(const std::vector<std::any>& args)
function, You should pass explicit value. If type of given parameters are not the same with info of binded function, It will throw std::bad_any_cast. - The binded function must uses
decltype(nullptr)
instead of void at return type('Cause we can't covert void type into std::any) and return nullptr.