c++ - 类 std::result_of 中没有名为 'type' 的类型

标签 c++ asynchronous future stdbind

以下代码无法编译:

template< typename Fn >  
bool templateFunctionOne( Fn&& fn )
{
   int v = 5;
   return fn( v );
}

template < typename Fn >
bool templateFunctionTwo( Fn&& fn )
{
   std::future< bool > tk( std::async( std::launch::async,
                           &templateFunctionOne< Fn >,
                           std::forward<Fn>(fn ) ) );
   return tk.get();
 }

 bool printThis( int value )
 {
   cout << value << endl;
   return true;
 }

 int main()
 {
    auto func = std::bind( &printThis, std::placeholders::_1 );
    return templateFunctionTwo( func );  
 }  

编译时出现如下错误:

functional::1665:61: error: no type named 'type' in 'class std::result_of< bool ((std::_Bind(std::_Placeholder<1>))(int)>))(std::_Bind))(int)>&)>'

我简化了上面的内容,但它仍然不会编译并出现相同的错误消息:

template< typename Fn >  
bool templateFunctionOne( Fn&& fn )
{
   return fn();
}

template < typename Fn >
bool templateFunctionTwo( Fn&& fn )
{
   std::future< bool > tk( std::async( std::launch::async,
                           &templateFunctionOne< Fn >,
                           std::forward<Fn>(fn ) ) );
   return tk.get();
 }

 bool printThis()
 {
   return true;
 }

 int main()
 {
    auto func = std::bind( &printThis );
    return templateFunctionTwo( func );  
 }  

因为现在函数 printThis 不需要传递任何参数,所以绑定(bind)调用不是必需的。当按如下方式更改 main 中的调用时,它编译得很好:

 int main()
 {
    return templateFunctionTwo( &printThis );  
 }  

谁能帮忙解释一下?在传递函数指针而不使用 std::ref 在需要其引用时包装参数时,我已经看到了同样的错误,但这似乎是别的东西(或不是),什么我在这里失踪了吗?

最佳答案

auto func = std::bind( &printThis );
return templateFunctionTwo( func );  

func是左值,所以当左值传入templateFunctionTwo时, Fn推导为 Fn& (由于转发引用)。

线下

&templateFunctionOne< Fn >,

表示

&templateFunctionOne< Fn& >,

这意味着templateFunctionOne通过引用接受它的论点, 如果你想在调用时通过引用传递参数 async 你需要使用包装器 std::refstd::cref :

   std::future< bool > tk =  std::async( 
               templateFunctionOne< Fn >,
               std::ref( std::forward<Fn>(fn) ) ); // <--- ref added

现在您的代码可以编译了。

另一种方法是使用 remove_reference_t<Fn>或者 typename std::remove_reference<Fn>::typeFn 中删除左值引用:

  std::future< bool > tk =  std::async( 
     templateFunctionOne< std::remove_reference_t<Fn> >, // <--- remove_reference_t added 
     std::forward<Fn>(fn)  );
     return tk.get();

然后 fn对象按值传递。这个版本比第一个好,因为调用

 templateFunctionTwo( std::bind( &printThis, std::placeholders::_1 ) )

ref 时失败使用,因为 ref只需要取左值。

关于c++ - 类 std::result_of 中没有名为 'type' 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53352886/

相关文章:

c++ - c++继承模板类的构造函数

c++ - 使用 SolvePnP 的 OpenCV 断言失败

用于异步 HTTP 客户端的 C++ 库

Future 的 Scala 命名约定

scala - 跟踪已完成的 future

c++ - 哪些类型的代码需要注意右值引用?

c++ - 逗号分隔语句中返回值的生命周期

java - MQ 队列与批处理 : how to replay asynchronous process when it fails

javascript - 使用 CasperJS 中的函数返回 iframe 内的链接

java - Guava CheckedFuture<X,Y> 映射到 CheckedFuture <Z,Y>,无阻塞