【发布时间】:2015-07-17 00:57:09
【问题描述】:
我正在尝试使用 std::bind 将右值引用绑定到 lambda,但是当我将其放入 std::async 调用时遇到问题:(source)
auto lambda = [] (std::string&& message) {
std::cout << message << std::endl;
};
auto bound = std::bind(lambda, std::string{"hello world"});
auto future = std::async(bound); // Compiler error here
future.get()
这会引发一个编译器错误,我不确定如何解释:
错误:'class std::result_of(std::basic_string)>&()>'中没有名为'type'的类型
这里发生了什么?有趣的是,稍作修改就可以按预期编译和工作。如果我将 std::string{"hello world"} 更改为 c 字符串文字,一切正常:(source)
auto lambda = [] (std::string&& message) {
std::cout << message << std::endl;
};
auto bound = std::bind(lambda, "hello world");
auto future = std::async(bound);
future.get(); // Prints "hello world" as expected
为什么这行得通,但不是第一个例子?
【问题讨论】:
-
如果 lambda 是用
auto lambda = [] (std::string& message)定义的(参考,而不是右值),它也可以工作 -
我也注意到了,虽然它应该是
const string& message,否则它会拒绝接受 c-string 文字。 -
让
async为你做绑定:std::async(lambda, std::string{"hello world"})。