How to store methods as function pointers in a map continer?

  • A+

I want to be able to call functions based on the data I read from file. So for each item type, I want to call the desired reader method. I wrote this code, but it does not compile where I want to add function pointers to the map. What is wrong ?

#include <vector> #include <map> #include <iostream> class reader {    std::map< std::string, void(*)()> functionCallMap; // function pointer   void readA(){ std::cout << "reading A/n";};   void readB(){ std::cout << "reading B/n";};; public:   reader()   {     *functionCallMap["A"] = &reader::readA;*     *functionCallMap["B"] = &reader::readB;*   }    void read()   {    auto (*f) = functionCallMap["A"];    (*f)();   }    }; 

I am filling the map at Constructor.


You need to use pointers to member functions, like this:

class reader {     using FuncPtr = void(reader::*)();     std::map< std::string, FuncPtr> functionCallMap; // function pointer     void readA(){ std::cout << "reading A/n"; }     void readB(){ std::cout << "reading B/n"; } public:     reader()     {         functionCallMap["A"] = &reader::readA;         functionCallMap["B"] = &reader::readB;     }      void read()     {         auto f = functionCallMap["A"];         (this->*f)();     } };  int main() {     reader r;; } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: