首页 > 解决方案 > std::function 指针错误:无法将 &A::a 转换为 std::function<>&& 类型

问题描述

我正在尝试将字符串映射到函数指针,以便我可以使用iter->second(arg)而不是 if-else 来调用函数。我写了一个没有 的简单的class,它按预期工作。但是当我如下修改它时,它会显示编译错误。

 #include <functional>
 #include <iostream>
 #include <unordered_map>
 #include <string>

 using std::string;

 class A{
     private:
     int a(int num, string s) { return s.size() + num; }
     int b(int num, string s) { return num - s.size(); }

     public:
     void ido(string str){
         typedef std::function<int(int, string)> process_func;
         std::unordered_map<string, process_func> m;
         m.insert(std::make_pair<string, process_func>("a", &A::a));
         // using std::placeholders::_1;
         // m.insert(std::make_pair<string, process_func>("a", std::bind(&A::a, this, _1)));
         // m["a"] = std::bind(&A::a, this, _1);
         // m.insert({{"a", &A::a}, {"b", &A::b}});

         auto x = m.find(str);
         if(x == m.end()) {
             std::cout << "Not supported!" << std::endl;
         }
         std::cout << x->second(10, "hello") << std::endl;
     }
 };
 int main(int argc, char* argv[]) {
     A a;
     a.ido(string(argv[1]));
     return 0;
 }

错误是:

function.cc: In member function ‘void A::ido(std::string)’:
function.cc:17:65: error: no matching function for call to ‘make_pair(const char [2], int (A::*)(int, std::string))’
         m.insert(std::make_pair<string, process_func>("a", &A::a));
                                                                 ^
function.cc:17:65: note: candidate is:
In file included from /usr/include/c++/4.8.2/utility:70:0,
                 from /usr/include/c++/4.8.2/tuple:38,
                 from /usr/include/c++/4.8.2/functional:55,
                 from function.cc:1:
/usr/include/c++/4.8.2/bits/stl_pair.h:276:5: note: template<class _T1, class _T2> constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)
     make_pair(_T1&& __x, _T2&& __y)
     ^
/usr/include/c++/4.8.2/bits/stl_pair.h:276:5: note:   template argument deduction/substitution failed:
function.cc:17:65: note:   cannot convert ‘&amp;A::a’ (type ‘int (A::*)(int, std::string) {aka int (A::*)(int, std::basic_string<char>)}’) to type ‘std::function<int(int, std::basic_string<char>)>&&’
         m.insert(std::make_pair<string, process_func>("a", &A::a));

错误是什么意思?如何解决?

标签: c++function-pointers

解决方案


虽然您的函数“a”和“b”不依赖于“this”(它们不访问 A 类中的任何内容),但编译器不够聪明,无法推断出这一点。所以该错误意味着您正在尝试将“指向方法的指针”转换为“指向函数的指针”,这是不正确的转换。“指向方法的指针”需要和要调用的对象。您需要将方法“a”和“b”声明为“静态”,以表明它们实际上是独立函数,而不是类的方法。


推荐阅读