Can std :: function accept functors?
I tried this small piece of code and to my surprise my compilers don't like it.
It works as expected if I remove write_by_call (h); line, but it doesn't compile if I leave it because it doesn't know the conversion from h, anonymous class, to std :: function for the 1st argument.
Is it expected? Does anyone know what the standard means 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...
+3
source to share
1 answer
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 posting public h::operator()
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...
+5
source to share