c++ - Calling functions from a std::map -
i'm trying construct object serve handler functions. explain why, i'll use scan user input, check map match. if match found, call function , copy rest of user-inputted line function;
class object { public: object(std::map<std::string, void(*)(const std::string&)> map) {/*...code...*/}; }; quick example code:
class main { public: void testfunc(const std::string& a) { } void construct() { object{ std::map<std::string, void(*)(const std::string&)> { {"exit", [](const std::string &a){ exit(1); }}, //{"test1", (void(main::*)(const std::string&))&testfunc}, //{"test2", [](const std::string &a){ testfunc(a); }}, //{"test3", [this](const std::string &a){ testfunc(a); }}, {"null", null} } }; } }; neither of commented lines worked, creating different errors, other lines succeeded , there no runtime errors (well, null be, i'm handling that).
my question is, imagining mechanics of properly, if not, should save pointers , cast functions later? possible save reference , call functions inside object defined inside class scope (calls made inside class too)?
a lot of questions.. know. i've never seen done before.. guess there might reason.
because didn't specify errors, here link;
non-static member functions different non-member functions in take implicit argument - class instance. main::testfunc requires 2 arguments: main , std::string const&. interface allows single argument. way make work create global main* function reference - terribly brittle design.
instead, make interface more generic using std::function<void(std::string const&)>. any callable takes std::string const&, instead of pointer function. allow write last version:
{"test3", [this](const std::string &a){ testfunc(a); }}, and best bet.
Comments
Post a Comment