作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在一些人的帮助下,我编译了以下代码(通过添加 '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/
我是一名优秀的程序员,十分优秀!