【发布时间】:2021-10-21 15:41:07
【问题描述】:
你想达到什么目的
我想将 RetType ClassA::MemberFunc(Args...) 转换为 mem_fn(&ClassA::MemberFunc) 但它就像一个函数,以避免为每个成员函数编写 lambda 或函数
你得到了什么(包括错误信息)
no matching function for call to ‘regisAdd(std::_Mem_fn<int (ABC::*)(int, int)>)’
这是我的代码。
#include <functional>
#include <iostream>
using namespace std;
struct ABC {
int value;
int add(int a, int b) {
return a + b * value;
}
int other(int a) {
return a * value;
}
};
int doAdd(void* data, int a, int b) {
ABC* p = (ABC*)data;
return p->add(a, b);
}
typedef int (*TYPE_ADD)(void* data, int a, int b);
TYPE_ADD gAdd = nullptr;
void regisAdd(TYPE_ADD a) {
gAdd = a;
}
void callAdd() {
if (!gAdd) return;
ABC abc;
abc.value = 10;
cout << gAdd(&abc, 1, 2) << endl;
}
typedef int (*TYPE_OTHER)(void* data, int a);
TYPE_OTHER gOther = nullptr;
void regisOther(TYPE_OTHER a) {
gOther = a;
}
void callOther() {
if (!gOther) return;
ABC abc;
abc.value = 10;
cout << gOther(&abc, 12) << endl;
}
int main() {
regisAdd(doAdd); // this is GOOD
callAdd(); // call
regisAdd([](void* data, int a, int b) { // < this is also GOOD
return static_cast<ABC*>(data)->add(a, b); // < GOOD
}); // < GOOD
callAdd(); // call
// how to write a general function work like mem_fn
// to avoid write doAdd and lambda for every function signatures
// regisAdd(mem_fn(&ABC::add));
// regisOther(mem_fn(&ABC::other));
// callAdd();
return 0;
}
【问题讨论】:
-
你如何为
callXXX选择参数? -
@Jarod42,这是简单的代码,真实世界的代码是有几个用 C 编写的函数指针成员的结构,我想将它们包装到 C++。
标签: c++ templates template-meta-programming