作者loveme00835 (发箍)
看板C_and_CPP
标题Re: [问题] cpp的function pointer传递
时间Thu Oct 1 09:24:17 2020
物件的操作需要以下两个资讯:
1. 物件的参考/指标 (pointer to object)
2. 该物件的成员参考/指标 (pointer to member)
因为你在 B::B_API() 里会存取到资料成员所以要把资讯透过额外的参数传递
给 pfnTest_t, 这通常得做 type erasing 来降低相依性, 不需要这个资讯的
话改传 null pointer 就好了. 这种设计在 task-based system 还蛮常见的.
typedef int(*pfnTest_t)(
void* context,
void* x,
unsigned char* y,
unsigned int z);
int test_api(pfnTest_t p_pfnTest,
void* context);
context 的内容要和 callback 实作相互搭配, 因为标准还不允许用整数型别
来储存 pointer to member 的资讯, 在这里只能先传物件指标作为引数:
int my_callback(
void* context,
void* x,
unsigned char* y,
unsigned int z) {
return reinterpret_cast<B*>(
context)->B_API(x, y, z);
}
B b;
test_api(my_callback, std::addressof(b));
上面的实作应该是最直觉的写法, 但却存在不少问题:
1. test_api() 呼叫叙述
无法表达会转呼叫 B::B_API() 这件事
2. my_callback() 和 B 耦合性太高,
修改范围无法只局限在一个地方
3. my_callback() 这类的
adapter function 实作数会与类别和成员组合
数呈正比
所以我们需要一种可以
将类别以及成员函式资讯内嵌在函式里方法, 并且
自动
产生需要的 adapter function, 在 C++ 里通常会用模板来实现. 因为类别是
成员函式型别的一部分, 我们只需要储存後者即可, 前者可以透过 meta-func
tion
class_of<pmf> 来取得:
template <
auto pmf>
struct class_of;
template <
typename Ret,
typename C,
typename... Args,
Ret (C::*pmf) (Args...)
>
struct class_of<pmf> {
using type = C;
};
static_assert(std::is_same_v<class_of<&B::B_API>::type, B>);
接着我们就可以用
class_of<pmf> 来实作 adapter function 产生器:
template <
auto pmf>
int delegate_to(
void* context,
void* x,
unsigned char* y,
unsigned int z) {
auto*
const object =
reinterpret_cast<
typename class_of<pmf>::type*>(context);
return (object->*pmf)(x, y, z);
}
test_api(
delegate_to<&B::B_API>, std::addressof(b));
完整程式码:
https://wandbox.org/permlink/8vEKgUbQojKeOAwK
透过以上程式码我们就能将更多心力放在商业逻辑, 而不用烦恼语言限制 :)
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 114.137.28.236 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1601515469.A.170.html
※ 编辑: loveme00835 (114.137.28.236 台湾), 10/01/2020 09:58:50
1F:→ Lipraxde: 但是,test_api 他不能改吧? 10/01 10:24
2F:→ Lipraxde: 把 B_API 改成 static 出错的地方也怪怪的 @@ 10/01 10:25
3F:推 sighAll: 谢谢! 10/21 22:48