简体   繁体   中英

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

So I got myself onto shaky ground by insisting on making a C++ class immitate a regular function. The class overloads the function operator, making it a functor, of course. This all works fine, until you want to pass the function pointer of this functor.

Naturally, I want to let the compiler know that we know what we're doing (lol), by doing a reinterpret_cast of this pointer. However, how do I get the address of this particular member function, since it is an overloaded operator. How does one get the address of that?

UPDATE: You asked for an example. Here is a minimal one.

So I have an interface, which I cannot change. It looks like this;

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

Now, this is quite straight-forward; the API is setting some callback function pointer. So, the idea was to implement the callback as a functor class, by overloading the operator() , like so, as usual.

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

Here comes the question; seeing as I cannot change the API used (the function that expects a function pointer of a certain signature), how can I then get the address of the member function and pass that?

I suspect it goes something like; someFunc(reinterpet_cast<some_callback_t>( ? ? ? )); to make sure that the compiler won't barf at me.

Supposing that you have to use a function pointer, and that your functor has no state, you can use a lambda as glue:

void takesFunctionPointer(void (*)());

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

// ...

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

How does one get the address of that?

In the same way as any other member function. The name of the function is class_name::operator() . An example:

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.

That's usually not what one would want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM