【问题标题】:std::function can take functors?std::function 可以带仿函数吗?
【发布时间】: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
  • 看了之后就很明显了……谢谢大家。

标签: function c++11 functor


【解决方案1】:

编译器错误信息确实有点误导:

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

【讨论】:

  • 如果仿函数没有任何私有内容,我更喜欢将class 更改为struct
猜你喜欢
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
相关资源
最近更新 更多