简体   繁体   中英

How do I compare a std::function's target with a member function's address?

I am trying to figure out how to compare a function object's target (which is a member function) with the actual member function. Of course, they should match.

But I don't get them to match, and I am lost with the syntax for declaring a member function as the type for the function object.

Here is some code:

#include <cstdlib>
#include <iostream>
#include <functional>
using namespace std;


class Object {
public:
    void method () {}
};


int main(int argc, char** argv) {

    Object* obj = new Object();
    function<?????> wrapper = bind(&Object::method, obj);
    if (wrapper.target<?????>() == &Object::method) {
        cout << "match" << "\n";
    } else {
        cout << "no match" << "\n";
    }   
    delete(obj);

    return 0;
}

I tried to put different things instead of the ?????, but without any success.

So, what do I write instead of the questions marks, or are there other problems with this code?

 function<?????> wrapper = bind(&Object::method, obj); 

The bind expression returns a callable object that requires no arguments and returns void , so the logical call signature is void() and so you want std::function<void()> .

 if (wrapper.target<?????>() == &Object::method) { 

This won't work, because the function doesn't hold the pointer-to-member-function, it holds the result of the bind expression, which wraps the pointer-to-member-function.

The type returned by the bind expression (and therefore the type of the function 's target) is some internal implementation detail such as _Binder<void, _Mem_fn<Object, void()>, Object*> , which you can't refer to directly.

You could do:

auto b = bind(&Object::method, obj);
function<void()> wrapper = b;
if (wrapper.target<decltype(b)>() != nullptr) {

But this doesn't tell you anything useful.

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