Calling a member function pointer stored in a std

2019-02-27 15:18发布

I'm storing a map in a class that has strings as keys and pointers to member functions as values. I'm having trouble calling the right function throw the function pointer. Here is the code:

#include <iostream>
#include <string>
#include <map>

using namespace std;


class Preprocessor;

typedef void (Preprocessor::*function)();



class Preprocessor
{

public:
    Preprocessor();
   ~Preprocessor();

   void processing(const string before_processing);

private:

   void   take_new_key();

   map<string, function>   srch_keys;

   string  after_processing;
};


Preprocessor::Preprocessor()
{
   srch_keys.insert(pair<string, function>(string("#define"), &Preprocessor::take_new_key));
}

Preprocessor::~Preprocessor()
{

}


void Preprocessor::processing(const string before_processing)
{
   map<string, function>::iterator result = srch_keys.find("#define");

   if(result != srch_keys.end())
      result->second; 
}


void Preprocessor::take_new_key()
{
   cout << "enters here";
}


int main()
{
   Preprocessor pre;
   pre.processing(string("...word #define other word"));

   return 0;
}

In function Preprocessor::processing if the string is found in the map then, I call the proper function. The problem is that, in this code, Preprocessor::take_new_key is never called.

Where is the mistake ?

Thanks

2条回答
趁早两清
2楼-- · 2019-02-27 15:54

The correct syntax is this:

(this->*(result->second))();

That is ugly. So lets try this:

auto mem = result->second;  //C++11 only
(this->*mem)();

Use whichever makes you happy.

查看更多
贼婆χ
3楼-- · 2019-02-27 15:56

result->second does not call the function pointer. Try ((*this).*result->second)();

查看更多
登录 后发表回答