3
我试过这段小小的代码,但我的编译器并不喜欢它。std :: function可以使用函子吗?
如果我删除write_by_call(h),它会按预期工作;行,但它不会编译,如果我离开它,因为它知道没有从匿名类h转换为第一个参数的std :: function。
是否预计?有谁知道std :: functions和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);
}
没有牵连线,如预期的输出:
hi, I am f
I am from the lambda!
I do not like this one...
你的'操作符()'是私人 – 2014-10-09 14:48:29
当要求与编译器错误的帮助,**必须说明错误**和编译器,编译器版本和操作系统的确切全文。 – 2014-10-09 14:49:45
公平起见,他没有问一个编译器错误,但问你是否可以在看到它后明显地将函数转换为std :: function – 2014-10-09 14:57:06