Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::function can take functors?

I tried this little piece of code and by my surprise my compilers do not like it.

It works as expected if I remove the write_by_call(h); line, but it does not compile if I leave it because it knows no conversion from h, the anonymous class, to std::function for 1st argument.

Is it expected? Do anyone knows what the standard states about std::functions and functors?

#include <functional>
#include <iostream>
#include <string>

void write_by_call(std::function<std::string ()> return_str_f) {
    if (return_str_f) {
        std::cout << return_str_f() << std::endl;
    } else {
        std::cout << "I do not like this one..." << std::endl;
    }
}

class {
    std::string operator()() {
        return std::string("hi, I am the class h");
    }
} h;


std::string f() {
    return std::string("hi, I am f");
}

auto g = []() { return std::string("I am from the lambda!"); };

int main() {
    write_by_call(f);
    write_by_call(g);
    write_by_call(h);
    write_by_call(nullptr);
}

Without the incriminated line the output is, as expected:

hi, I am f
I am from the lambda!
I do not like this one...
like image 624
Paolo.Bolzoni Avatar asked Sep 16 '25 14:09

Paolo.Bolzoni


1 Answers

The compiler error message is admittedly a bit misleading:

main.cpp: In function 'int main()':
main.cpp:29:20: error: could not convert 'h' from '<anonymous class>' to 'std::function<std::basic_string<char>()>'
     write_by_call(h);

but making h::operator() public seems to fix this:

class {
    public:
        std::string operator()() {
            return std::string("hi, I am the class h");
    }
} h;

Output:

hi, I am f
I am from the lambda!
hi, I am the class h
I do not like this one...
like image 180
Paul R Avatar answered Sep 18 '25 09:09

Paul R