Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

Kode example:

#include <vector>
#include <functional>
#include <iostream>
using namespace std;

void Foo() {
    cout << "Hi" << endl;
}

int main() {

    auto f = Foo;

    vector<function<void()>> vec;
    vector<function<void()>>::iterator it;

    vec.emplace_back(Foo);

    for (it = vec.begin(); it < vec.end(); it++) {
        // how to evaluate if (it == f)?

        //if (*it == f) { // Error
        //  
        //}
    }
}

Variabels values and points values in the above example:
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading