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...
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With