调用存储在标准映射中的成员函数指针 [英] Calling a member function pointer stored in a std map

查看:98
本文介绍了调用存储在标准映射中的成员函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将地图存储在一个类中,该类具有字符串作为键,而指向成员函数的指针作为值.我在调用正确的函数时遇到了麻烦,即抛出了函数指针. 这是代码:

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;
}

在函数Preprocessor::processing中,如果在映射中找到该字符串,则调用适当的函数.问题在于,在此代码中,从未调用Preprocessor::take_new_key.

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.

错误在哪里?

谢谢

推荐答案

正确的语法是这样的:

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

那太丑了.因此,让我们尝试一下:

That is ugly. So lets try this:

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

使用使您感到快乐的任何方式.

Use whichever makes you happy.

这篇关于调用存储在标准映射中的成员函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆