std :: function可以带函子吗?

Pao*_*oni 3 function functor c++11

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

如果我删除write_by_call(h),它会按预期工作; 如果我离开它,它就不会编译,因为它知道没有从h(匿名类)到第一个参数的std :: function的转换.

这是预期的吗?有谁知道关于std :: functions和functor的标准是什么?

#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);
}
Run Code Online (Sandbox Code Playgroud)

没有受到控制的线路,输出就像预期的那样:

hi, I am f
I am from the lambda!
I do not like this one...
Run Code Online (Sandbox Code Playgroud)

Pau*_*l R 5

编译器错误消息无疑是有点误导:

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);
Run Code Online (Sandbox Code Playgroud)

h::operator()公开似乎解决了这个问题:

class {
    public:
        std::string operator()() {
            return std::string("hi, I am the class h");
    }
} h;
Run Code Online (Sandbox Code Playgroud)

输出:

hi, I am f
I am from the lambda!
hi, I am the class h
I do not like this one...
Run Code Online (Sandbox Code Playgroud)

  • 如果仿函数没有任何私有内容,我更喜欢将`class`改为`struct`. (2认同)