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)
到astd::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);
}