c++ - 将指向成员函数的指针转换为 std::function

标签 c++ c++11 function-pointers pointer-to-member std-function

我有一个稍微复杂的用例,将成员函数指针传递给外部函数,然后由成员函数再次调用该函数(不要问!)。我正在学习std::functionstd::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/

相关文章:

c++ - 为什么我的 vector 会丢弃它的数据?

c++ - 使用函数指针调用函数模板

c++ - 将类函数指针转换为 void* 或反之

c++ - 两个数组之间的数据聚类和比较

c++ - 迭代某个类的 vector 列表 (C++)

c++ - 如何像普通 C 函数一样使用正确的 'this' 指针调用 C++ 类成员函数? (指向类成员函数的指针)

c++ - C++11标准§12.6.2/2中单词 "constructor' s class"的解释

c++ - 从 C++ 中的字符串中删除双引号

c++ - "Insert before"用于 std::list

c++ - 将函数指针从一种类型转换为另一种类型的最佳方法是什么?