gpt4 book ai didi

c++ - 模板增加扣除/替换失败

转载 作者:行者123 更新时间:2023-11-30 04:54:56 26 4
gpt4 key购买 nike

在一些人的帮助下,我编译了以下代码(通过添加 '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)
^~~~~~~~

谁能帮我解决这个问题?

最佳答案

this 绑定(bind)时位置错误:

   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 ) ) ;

关于c++ - 模板增加扣除/替换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53356146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com