3

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.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
GråSkærm
  • 45
  • 4
  • 6
    No images of errors or code, or otherwise plain text please! – πάντα ῥεῖ Mar 04 '22 at 14:24
  • 3
    `std::function` is a type-erasing wrapper around any kind of callable. AFAIK there is no way to check what function it actually wraps. `operator==` can only check if the `std::function` has a callable in it or not, not which one it is. – super Mar 04 '22 at 14:29
  • 1
    IMO this is [XY problem](http://mywiki.wooledge.org/XyProblem). Please explain what your code should do, then we can provide proper solution which will not require comparing `std::function`. – Marek R Mar 04 '22 at 14:33
  • Possible duplicate of [Comparing std::functions for equality?](https://stackoverflow.com/questions/20833453/comparing-stdfunctions-for-equality) – Wyck Mar 04 '22 at 14:45
  • `it < vec.end()` should be `it != vec.end()`. – Eljay Mar 04 '22 at 14:56

1 Answers1

6

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.)

auto f = Foo; // This pointer existed in an earlier version of the question

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

or:

*it->target< decltype(&Foo) >() == Foo
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180