C++ 将 class 的重载 operator() 作为函数指针传递

C++ passing overloaded operator() of class as function pointer

因此,我坚持让 C++ class 模仿常规函数,从而让自己陷入了摇摇欲坠的境地。 class 重载了函数运算符,当然使它成为一个函子。这一切都很好,直到你想传递这个仿函数的函数指针。

自然地,我想让编译器知道我们知道我们在做什么(笑),通过对这个指针做一个reinterpret_cast。但是,我如何获取这个特定成员函数的地址,因为它是一个重载运算符。如何获得它的地址?

更新:您要求举个例子。这是一个最小的。

所以我有一个界面,我无法更改。看起来像这样;

typedef void (*some_callback_t)(SomeType);'
void someFunc(some_callback_t);

现在,这很简单; API 正在设置一些回调函数指针。因此,我们的想法是像往常一样通过重载 operator() 将回调实现为仿函数 class。

class Bah {
  void operator()(SomeType);
};

问题来了;鉴于我无法更改使用的 API(需要某个签名的函数指针的函数),我如何才能获取成员函数的地址并传递它?

我怀疑它是这样的; someFunc(reinterpet_cast<some_callback_t>( ? ? ? )); 以确保编译器不会对我吐槽。

How does one get the address of that?

与任何其他成员函数一样。函数的名称是 class_name::operator()。一个例子:

struct class_name {
    void operator()(){}
};

void (class_name::*member_function_pointer)() = &class_name::operator();
class_name instance;
(instance.*member_function_pointer)(); // in a block scope

Naturally, I want to let the compiler know that we know what we're doing (lol), by doing a reinterpret_cast of this pointer.

这通常不是人们想要做的。

假设您使用函数指针,并且您的仿函数没有状态,您可以使用 lambda 作为胶水:

void takesFunctionPointer(void (*)());

struct MyFunctor {
    void operator()();
};

// ...

takesFunctionPointer([] { return MyFunctor{}(); });