gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:27:49 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com