我有一个稍微复杂的用例,将成员函数指针传递给外部函数,然后由成员函数再次调用该函数(不要问!)。我正在学习std::function
和std::mem_fn
但我似乎无法转换我的旧学校函数指针
void (T::*func)(int)
到 std::function<void (T::*)(int) func>
在下面的代码中,我希望能够将 std::function 传递给 memFuncTaker
在来自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);
}
最佳答案
当您绑定(bind)std::function
时对于非静态成员函数指针,它“揭示”了隐藏的 this
参数,使其成为结果仿函数的第一个显式参数。所以在你的情况下 outer::aMember
你会使用std::function<void(outer *, int)>
最终得到一个二参数仿函数
#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);
}
http://coliru.stacked-crooked.com/a/5e9d2486c4c45138
当然,如果您愿意,您可以绑定(bind)该仿函数的第一个参数(通过使用 std::bind
或 lambda),从而再次“隐藏”它
#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);
}
请注意,在此版本中memFuncTaker
不再必须是模板(这恰好是 std::function
的主要目的之一 - 采用类型删除技术来“去模板化”代码)。
关于c++ - 将指向成员函数的指针转换为 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47047657/