【问题标题】:Does std::unordered_map<std::string,std::function<void(std::string&) can hold only static functions?std::unordered_map<std::string,std::function<void(std::string&) 只能保存静态函数吗?
【发布时间】:2015-05-29 16:21:21
【问题描述】:

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

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

main.cpp:15:11: 错误:没有匹配的成员函数调用 '插入'

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

【问题讨论】:

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


    【解决方案1】:

    在这种情况下,您的 std::function 类型是错误的。对于成员函数Example::processString(std::string&amp;)

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

    但是,您可以通过提前绑定来避免这种情况并“吃掉”this 参数:

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

    现在唯一未绑定的参数是字符串引用,所以类型可以保留:

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

    【讨论】:

    • 不确定你是否对我只是在编辑它很酷,所以想我会发表评论。无论如何,+1。
    • @Barry:干杯(仅供参考:不会介意;这显然只是一个小小的疏忽)
    • @LightnessRacesinOrbit 谢谢澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2011-03-26
    相关资源
    最近更新 更多