【问题标题】:C++ Map of string and member function pointer字符串和成员函数指针的 C++ 映射
【发布时间】:2013-01-19 21:46:14
【问题描述】:

嘿,所以我正在制作一个以字符串为键、成员函数指针为值的映射。我似乎无法弄清楚如何添加到地图,这似乎不起作用。

#include <iostream>
#include <map>
using namespace std;

typedef string(Test::*myFunc)(string);
typedef map<string, myFunc> MyMap;


class Test
{
private:
    MyMap myMap;

public:
    Test(void);
    string TestFunc(string input);
};





#include "Test.h"

Test::Test(void)
{
    myMap.insert("test", &TestFunc);
    myMap["test"] = &TestFunc;
}

string Test::TestFunc(string input)
{
}

【问题讨论】:

  • 猜测,但&amp;Test::TestFunc?
  • 似乎修复了参数中的一个错误,但我仍然收到插入错误
  • @Kosmo 那是因为insert 不能那样工作。
  • “这似乎不起作用”是什么意思?
  • 具体一点,引用错误。关于 insert(),您必须将其转换为正确的类型,即 pair,又名 map::value_type。

标签: c++ map member-function-pointers


【解决方案1】:

请参阅std::map::insertstd::map 了解value_type

myMap.insert(std::map<std::string, myFunc>::value_type("test", &Test::TestFunc));

对于operator[]

myMap["test"] = &Test::TestFunc;

您不能在没有对象的情况下使用指向成员函数的指针。您可以将指向成员函数的指针与Test 类型的对象一起使用

Test t;
myFunc f = myMap["test"];
std::string s = (t.*f)("Hello, world!");

或使用指向类型Test的指针

Test *p = new Test();
myFunc f = myMap["test"];
std::string s = (p->*f)("Hello, world!");

另见C++ FAQ - Pointers to member functions

【讨论】:

  • +1,虽然因为 std::map&lt;A,B&gt;::value_typepair&lt;const A,B&gt; 我更喜欢插入 MyMap::value_type(a, b) 而不是 std::make_pair(a,b) 否则你会得到 pair&lt;A,B&gt; 必须转换为 pair&lt;const A,B&gt; 并且该转换不能被省略。
  • @OlafDietsche +1 不错的收获!
  • 我只是想知道将字符串文字传递给 make_pair 是否应该工作?毕竟,隐含的模板类型是 char[5],而不是 std::string 之类的。
  • @doomster,它是 const char[5],在 C++03 中 make_pair 按值获取参数,因此数组衰减到参数列表中的指针,并且在 C++11 中,返回类型使用 std::decay::type`,它也衰减为指针。所以它工作得很好。
  • @doomster 你是对的,这将是std::pair&lt;const char*, ...&gt; 而不是std::pair&lt;std::string, ...&gt;。虽然可行,但应该首选 Jonathan Wakely 的版本。
猜你喜欢
  • 2013-10-12
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多