How to create map in c++ and be able to search for function and call it?

前端 未结 7 908
予麋鹿
予麋鹿 2021-01-01 15:25

I\'m trying to create a map of string and method in C++, but I don\'t know how to do it. I would like to do something like that (pseudocode):

map

        
相关标签:
7条回答
  • 2021-01-01 16:14

    This is indeed possible in C++, thanks to function pointers. Here's a simple example:

      std::string foo() { return "Foo"; }
      std::string bar() { return "Bar"; }
    
      int main()
      {
          std::map<std::string, std::string (*)()> m;
    
          // Map the functions to the names
          m["foo"] = &foo;
          m["bar"] = &bar;
    
          // Display all of the mapped functions
          std::map<std::string, std::string (*)()>::const_iterator it = m.begin();
          std::map<std::string, std::string (*)()>::const_iterator end = m.end();
    
          while ( it != end ) {
              std::cout<< it->first <<"\t\""
                  << (it->second)() <<"\"\n";
              ++it;
          }
      }
    

    This gets more tricky when dealing with functions with different return types and arguments. Also, if you are including non-static member functions, you should use Boost.Function.

    0 讨论(0)
提交回复
热议问题