模板扩充推论/替换失败

时间:2018-11-17 22:29:54

标签: c++ templates bind

在这里有人的帮助下,我编译了以下代码(通过添加'remove_reference'):

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< typename std::remove_reference<Fn >::type >,
                          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 );  
}  

这可以编译。现在,如果我将两个模板函数包装到一个结构中,并从其继承类的对象中调用它,则它将无法正常工作:

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

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

struct TestChild: public TestParent
{
   bool printThis( int );
   bool test();
};

bool TestChild::printThis( int value )
{
  return true;
}

bool Testchild::test()
{
   auto func = std::bind( &TestChild::printThis, std::placeholders::_1, this);  
   return templateFunctionTwo( func );
}

int main()
{
   TestChild myTest;
   myTest.test();
   return 0;
}

错误:

no matching for call to '(std::_Bind< bool ( TestChild::\*(std::_Placeholder<1>, TestChild*))(int) >) (int&)'   
     return fn( val )  
             ~~~~~~^~~~~~~  


functional:547:2: note: candidate: template< class ... _Args, class
_Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...)  [with _Arg = {_Args ...}; _Result =
_Result; _Functor = bool (TestChild::\*)(int); _Bound_args = {std::_Placeholder<1>, TestChild*}]    operator()( _Args&&... __args)  
^~~~~~~~

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

this在绑定时在错误的位置:

   auto func = std::bind( &TestChild::printThis, this, std::placeholders::_1);  
                                                 ^^^^

必须作为第二个参数。

第二个问题,您没有调用async函数,而是尝试调用future ctor:

   std::future< bool > 
              tk ( std::launch::async,
                   &TestParent::templateFunctionOne< typename std::remove_reference<Fn>::type >,  
                   this, 
                   std::forward<Fn>( fn ) ) )  

应为:

 std::future< bool > 
          tk = std::async( std::launch::async,
               &TestParent::templateFunctionOne< typename std::remove_reference<Fn>::type >,  
               this,
               std::forward<Fn>( fn ) ) ;