Domanda

is it possible to rebuild the connection back from a std::function pointer back to an std::shared_ptr<> object instance? I wanna know to which object holds this std::function<> it's function ptr.

For example:

class Foo {
public:
    void doIt1( int i );
    void doIt2( int i );
};

void f() {
    std::shared_ptr<Foo> ptr( new Foo );

    std::function<void(int)> fp = get_funcptr_from_somewhere();

    if( fp.target<void(int)>() == ptr ) {
        // I've found it!!
    }

}

The problem is fp.target is only a function ptr and I could build a function pointer again out of ptr but this I don't know which function of that object it is pointless (interestingly target reports nullptr if the object was deleted). Which does help, but is there any other possibility to correlate an std::function<> object to an existing std::shared_ptr instance?

Thank you very much!

È stato utile?

Soluzione 2

First, ptr is not invokable, so it cannot be the target of std::function<void(int)>. The only objects that can be the target of std::function<void(int)> are those that can be invoked with (int).

This is generally true of every std::shared_ptr -- there are no invokable std::shared_ptrs, so they are never the target of a std::function.

An object is invokable if you can go object( blah ) for some blah.

target<X>() only returns non-nullptr if the invokable object stored is exactly of type X. If you have stored a bind or mem_fun expression, this means there is no way practical to get it back out.

You can arrange so that your std::functions are constructed in very particular ways using very particular types, and on that subset of std::functions use target<X>() to extract out the backing objects, but this is not generally a useful technique, and is instead intended for narrow special cases.

Altri suggerimenti

The C++ standard defines for function objects in [function.objects] (12.8) only their names and the effect they have. It does not specify a concrete implementation.

So if you have an std::function function object there is no way of knowing what function with what arguments it will call.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top