C++ 将指向成员函数的指针转换为std::函数

C++ 将指向成员函数的指针转换为std::函数,c++,c++11,function-pointers,member-function-pointers,std-function,C++,C++11,Function Pointers,Member Function Pointers,Std Function,我有一个稍微复杂的用例,将成员函数指针传递到外部函数,然后由成员函数再次调用(不要问!)。我正在学习std::function和std::mem\u fn,但我似乎无法转换我的老式函数指针 void(T::*func)(int)到astd::function 在下面的代码中,我希望能够在从anotherMember #include "class2.hpp" #include <iostream> class outer{ public: void aMember(in

我有一个稍微复杂的用例,将成员函数指针传递到外部函数,然后由成员函数再次调用(不要问!)。我正在学习
std::function
std::mem\u fn
,但我似乎无法转换我的老式函数指针

void(T::*func)(int)
到a
std::function

在下面的代码中,我希望能够在从
anotherMember

#include "class2.hpp" 
#include <iostream> 

class outer{ 
public: 
  void aMember(int a){ 
    std::cout << a <<std::endl; 
  } 
  void anotherMember(double){ 
    memFuncTaker(this, &outer::aMember); 
  } 

}; 


template<class T> 
void memFuncTaker(T* obj , void (T::*func)(int) ){ 
  (obj->*func)(7); 
} 
#包括“class2.hpp”
#包括
类外部{
公众:
无效成员(int a){

std::cout当您将
std::function
绑定到非静态成员函数指针时,它会“显示”隐藏的
参数,使其成为结果函子的第一个显式参数。因此,对于
outer::aMember
而言,您将使用
std::function
并最终得到一个双参数函子

#include <functional>
#include <iostream> 

template<class T> 
void memFuncTaker(T *obj , std::function<void(T *, int)> func){ 
  func(obj, 7);
} 

class outer{ 
public: 
  void aMember(int a){ 
    std::cout << a <<std::endl; 
  } 
  void anotherMember(double){ 
    memFuncTaker(this, std::function<void(outer *, int)>{&outer::aMember}); 
  } 
}; 

int main() {
  outer o;
  o.anotherMember(0);
}

请注意,在此版本中,
memFuncTaker
不再必须是模板(这恰好是
std::function
的主要目的之一-使用类型擦除技术来“反模板化”代码)。

我没有看到任何尝试在代码中使用
std::function
。您的问题标题是“将指向成员函数的指针转换为std::function”,但问题听起来像是“将std::function转换为指向成员函数的指针”。std::bind(&outer::aMember,this,_1)的返回类型是什么
std::function
。我知道
aMember
是一个成员函数,但为什么
this
没有显示绑定到
std::function
的函数签名。我期望
std::bind(&outer::aMember,this,_1)
返回
std::function
@创造论者:为什么?该
std::bind
的全部目的是消除(绑定)第一个(
outer*
)参数。在
std::bind
之前,functor有两个参数-
outer*
int
,但在
std::bind
之后,只剩下一个参数:
int
。另一个例子是,如果你做了
std::mem\u fn(&outer::aMember)
你会得到一个双参数函数(就像你描述的那样).但是如果在这之后您执行了
std::bind(std::mem\u fn(&outer::aMember),那么这,_1)
只剩下一个参数。您在我上面的回答中看到的是相同的事情,因为
std::mem\fn
在这种上下文中是可选的,可以省略。
std::bind
足够聪明,可以在不显式应用
std::mem\fn
的情况下实现其含义。
#include <functional>
#include <iostream> 

using namespace std::placeholders;

void memFuncTaker(std::function<void(int)> func){ 
  func(7);
} 

class outer{ 
public: 
  void aMember(int a){ 
    std::cout << a <<std::endl; 
  } 
  void anotherMember(double){ 
    memFuncTaker(std::function<void(int)>(std::bind(&outer::aMember, this, _1))); 
  } 
}; 

int main() {
  outer o;
  o.anotherMember(0);
}