Home > Mobile >  Evaluating if (function<void()> == functor)?
Evaluating if (function<void()> == functor)?

Time:03-05

How can I evaluate given expression (function<void()> == functor).

Code example:

#include <functional>
using namespace std;

void Foo() { }

int main() {

    function<void()> a;
    // if (a == Foo) -> error
}

Edit: debugging details, and remove picture.

CodePudding user response:

std::function::target() will retrieve a pointer to the stored callable object. And that's what you're trying to compare.

You must specify the expected stored type, and target() will return nullptr if the type does not match.

(This means that if std::function holds a function pointer, target() will return a pointer-to-a-function-pointer.)

    if (*it->target<decltype(f)>() == f) { // Success

See it work in Compiler Explorer


Note that because functions decay to function pointers:

*it->target<decltype(Foo)>() == Foo

will not work, because std::function can not possibly be holding a copy of the function Foo. You would need to decay the function, such as:

*it->target< std::decay_t<decltype(Foo)> >() == Foo
  •  Tags:  
  • c
  • Related