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

我的梦境 提交于 2021-01-28 20:17:38

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35175834/how-do-i-compare-a-stdfunctions-target-with-a-member-functions-address

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!