In my school we're highly encouraged to use arrays of pointers to members instead of switch (or multiple else if) in C++ (and C).
As I don't see any point of using such arrays (I actually use maps of pointers to members) instead of a switch statement, I'd like to know if there's really any kind of optimization that would recommend pointers to functions.
Here's what's making me think that It'd be better to use switch :
Arrays (especially maps) of pointers to members are memory heavy (an std::string as key and a pointer as value) and need to be stored either in the class (doesn't make any sense since it's not an object property...) or re-created everytime in the function using them if declared statically :
std::map<std::string, void (MyClass::*)(...)> operations;
They're a pain to instantiate and get ready to use :
operations.insert(std::map<std::string, void (Parser::*)(std::vector<std::string> const &)>::value_type("push", &Parser::push)); operations.insert(std::map<std::string, void (Parser::*)(std::vector<std::string> const &)>::value_type("pop", &Parser::pop)); operations.insert(std::map<std::string, void (Parser::*)(std::vector<std::string> const &)>::value_type("dump", &Parser::dump)); operations.insert(std::map<std::string, void (Parser::*)(std::vector<std::string> const &)>::value_type("assert", &Parser::assert)); operations.insert(std::map<std::string, void (Parser::*)(std::vector<std::string> const &)>::value_type("add", &Parser::add)); operations.insert(std::map<std::string, void (Parser::*)(std::vector<std::string> const &)>::value_type("sub", &Parser::sub)); operations.insert(std::map<std::string, void (Parser::*)(std::vector<std::string> const &)>::value_type("mul", &Parser::mul)); operations.insert(std::map<std::string, void (Parser::*)(std::vector<std::string> const &)>::value_type("div", &Parser::div)); operations.insert(std::map<std::string, void (Parser::*)(std::vector<std::string> const &)>::value_type("mod", &Parser::pop)); operations.insert(std::map<std::string, void (Parser::*)(std::vector<std::string> const &)>::value_type("print", &Parser::print)); operations.insert(std::map<std::string, void (Parser::*)(std::vector<std::string> const &)>::value_type("exit", &Parser::exit));
It forces you to have useless parameters in some functions and to have non-const members that could've been const. For exemple, in my previous piece of code, "print" and "assert" could have been const if they were not used in the map, and most of the functions aren't using the parameter, but "push" and "assert" are...
You have to verify that the pointer you want to use exists in the map, instead of just letting the "default" case handle it, and the call is hard to read :
if (operations.find(myOperation) != operations.end()) (this->*(operations.find(myOperation)->second))(myParameter);
So why are we forced to use pointers to members instead of just a clear switch statement, or even else-ifs ?
Thanks.