std :: unordered_map <std :: string,std :: function <void(std :: string&)can =“”hold =“”only =“”static =“”functions?=“”

时间:2015-05-29 16:21:21

标签: c++ c++11 c++14

=“”

这是此问题的延续c++ function ptr in unorderer_map, compile time error

我试图使用std::function代替函数指针,只有当函数是静态的时候我才能插入函数。否则我会得到以下错误

  

main.cpp:15:11:错误:没有匹配的成员函数来调用   &#39;插入&#39;

  map.insert(std::make_pair("one",&Example::procesString));
#include<string>
#include <unordered_map>
#include<functional>

namespace Test
{
 namespace Test
{
  class Example
  {
  public:
    Example()
    {

      map.insert(std::make_pair("one",&Example::procesString));
    }
    static void procesString(std::string & aString)
    //void procesString(std::string & aString) -> compiler error 
    {

    }
    static  void processStringTwo(std::string & aString)
    {

    }

    std::unordered_map<std::string,std::function<void(std::string&)>> map;
  };
}
}

int main()
{
  return 0;
}

1 个答案:

答案 0 :(得分:4)

在此上下文中,您的std::function类型错误。对于成员函数Example::processString(std::string&)

std::function<void(Example*, std::string&)>

然而,你可以避免这种情况并且&#34;吃掉&#34;早期绑定this参数:

using std::placeholders;
map.insert(std::make_pair("one", std::bind(&Example::processString, this, _1));

现在唯一不带参数的参数是字符串引用,因此类型可以保留:

std::function<void(std::string&)>