为什么在C++ 11中没有std::protect和它一起使用?std::bind
Boost.Bind提供了一个boost::protect帮助器,它包装了它的参数,因此boost::bind无法识别和评估它.std::[c]ref在大多数情况下,它将是一个足够好的替代品,除了它不会将右值作为参数.
举一个具体的例子,考虑以下人为情况:
#include <type_traits>
#include <functional>
int add(int a, int b)
{ return a + b; }
struct invoke_with_42
{
template <typename FunObj>
auto operator()(FunObj&& fun_obj) const -> decltype((fun_obj(42)))
{ return fun_obj(42); }
};
int main()
{
//// Nested bind expression evaluated
//auto bind_expr =
// std::bind<int>(invoke_with_42{}
// , std::bind(&add, 1, std::placeholders::_1));
//// Compilation error, cref does not take rvalues
//auto bind_expr =
// …Run Code Online (Sandbox Code Playgroud) 我正在尝试将一个rvalue引用绑定到一个lambda使用std::bind,但是当我把它扔进一个std::async调用时我遇到了问题:( 来源)
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()
Run Code Online (Sandbox Code Playgroud)
这会发出编译器错误我不确定如何解释:
错误:'class std :: result_of(std :: basic_string)>&()>'中没有名为'type'的类型
这里发生了什么?有趣的是,稍微修改确实可以按预期编译和工作.如果我改为std::string{"hello world"}c字符串文字,一切正常:( 来源)
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
Run Code Online (Sandbox Code Playgroud)
为什么这有效但不是第一个例子?