Function 函数可以接受函子吗?

Function 函数可以接受函子吗?,function,c++11,functor,Function,C++11,Functor,我尝试了这段代码,但令我惊讶的是,我的编译器不喜欢它 如果我删除write_by_调用(h),它将按预期工作;行,但如果我离开它,它不会编译,因为它不知道从匿名类h到第一个参数的std::function的转换 这是预期的吗?有人知道标准中关于std::函数和函子的规定吗 #include <functional> #include <iostream> #include <string> void write_by_call(std::function&l

我尝试了这段代码,但令我惊讶的是,我的编译器不喜欢它

如果我删除write_by_调用(h),它将按预期工作;行,但如果我离开它,它不会编译,因为它不知道从匿名类h到第一个参数的std::function的转换

这是预期的吗?有人知道标准中关于std::函数和函子的规定吗

#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);
}

无可否认,编译器错误消息有点误导:

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);
输出:

hi, I am f
I am from the lambda!
hi, I am the class h
I do not like this one...

你的
操作符()
是私密的当你请求帮助处理编译器错误时,一定要说明错误的确切全文以及编译器、编译器版本和操作系统。公平地说,他没有问编译器错误,而是问一个函子是否可以转换成std::Function,这在你看到它之后是显而易见的。。。谢谢大家。如果functor没有任何私有内容,我更喜欢将
更改为
结构
class {
    public:
        std::string operator()() {
            return std::string("hi, I am the class h");
    }
} h;
hi, I am f
I am from the lambda!
hi, I am the class h
I do not like this one...