std :: function可以带函子吗?

时间:2014-10-09 14:44:30

标签: function c++11 functor

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

如果删除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);
}

如果没有被控制的行,输出就像预期的那样:

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

1 个答案:

答案 0 :(得分: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);

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

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...