物件的操作需要以下两个资讯:
  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
透过以上程式码我们就能将更多心力放在商业逻辑, 而不用烦恼语言限制 :)