【发布时间】:2014-10-09 14:44:29
【问题描述】:
我尝试了这段小代码,但令我惊讶的是我的编译器不喜欢它。
如果我删除 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...
【问题讨论】:
-
你的
operator()是私人的 -
在就编译器错误寻求帮助时,始终说明错误的确切全文以及编译器、编译器版本和操作系统。
-
说句公道话,他并没有问编译器错误,而是问是否可以将仿函数转换为 std::function
-
看了之后就很明显了……谢谢大家。