Bill Lumbert
Bill Lumbert

Reputation: 5003

std::function and comparison of std::function

I have the following function

typedef std::function<void(const data<3> & data, void * userData )> callbackFnc;

and some structure

typedef struct
{
  callbackFnc callback;
  void * userData;
} callbackData;

I store all these inside of my class in vector

std::vector<std::shared_ptr<callbackData> > mCallbacks;

This is how I add it:

bool MyClass::addCallback(callbackFnc cbFunc, void * userData)
{
std::shared_ptr<callbackData> cb = std::make_shared<callbackData>();
    cb->callback = cbFunc;
    cb->userData = userData;

    mCallbacks.push_back(cb);
}

Now I want to check that the given function has been added and remove it. To do this I just compare function's address like this:

for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++)
{
    // Compare address of these two functions
    if ((&(*it)->callback) == &cbFunc)
    {
        mCallbacks.erase(it);

        result = true;
        break;
    }
}

Looks like this comparison is not correct, but I can't figure out why. Any advice will be useful.

Thanks!

Upvotes: 2

Views: 2619

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118310

A std::function is not a function pointer. You cannot compare std::functions like you compare function pointers. If you comparing two std::functions, and expecting them to compare equal to each if they've type-erased the same function, that's not going to work. A std::function can only be compared to a nullptr. This is the only defined equality operator for std::functions.

Your goal is to identify a std::function and remove it from a vector of installed callback functions. The usual way this kind of functionality is done is by assigning a separate label to a wrapped function, often a std::string that gives a unique name to each function, and then you find the function by name. It doesn't have to be a std::string, an enum will work just as well. The bottom line is that you will have to establish how your std::functions are identified "out of band".

Upvotes: 9

Related Questions