2014-10-09 62 views
3

我试过这段小小的代码,但我的编译器并不喜欢它。std :: function可以使用函子吗?

如果我删除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... 
+6

你的'操作符()'是私人 – 2014-10-09 14:48:29

+1

当要求与编译器错误的帮助,**必须说明错误**和编译器,编译器版本和操作系统的确切全文。 – 2014-10-09 14:49:45

+0

公平起见,他没有问一个编译器错误,但问你是否可以在看到它后明显地将函数转换为std :: function – 2014-10-09 14:57:06

回答

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

如果仿函数没有任何私有内容,我更喜欢将'class'更改为'struct'。 – 2014-10-09 14:51:14

相关问题