问题
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