以下代码无法编译:
template< typename Fn1, typename Fn2 >
bool templateFunctionOne( Fn1&& fn1, Fn2&& fn2 )
{
int v = 5;
fn1( v );
return fn2( v );
}
template < typename Fn1, typename Fn2 >
bool templateFunctionTwo( Fn1&& fn1, Fn2&& fn2 )
{
std::future< bool > tk( std::async( std::launch::async,
&templateFunctionOne< typename std::remove_reference<Fn1>::type,
typename std::remove_reference<Fn2>::type >,
std::forward<Fn1>(fn1),
std::forward<Fn2>(fn2) ) );
return tk.get();
}
bool printThis( int value )
{
cout << "this value = "
<< value
<< endl;
return true;
}
bool printThat( int value )
{
cout << "that value = "
<< value
<< endl;
return true;
}
int main()
{
auto func1 = std::bind( &printThis, std::placeholders::_1 );
auto func2 = std::bind( &printThat, std::placeholders::_2 );
return templateFunctionTwo( func1, func2 );
}
我遇到这样的错误:
error: no match for call to '(std::_Bind<boo (*(std::_Placeholder<2>))(int)>) (int&)'
return fn2( thatValue );
~~~^~~~~~~~~~~~~
template argument deduction/substitution failed:
candidate: template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) const [with _Args = {_Args ...}; _Result = _Result; _Functor = bool (*)(int); _Bound_args = {std::_Placeholder<2>}]
operator()(_Args&&... --args) cont
^~~~~~~~
我知道这与将多个函数指针传递给模板有关,但是只是不知道在哪里和什么。有人可以帮我指出我的错误在哪里吗?
答案 0 :(得分:0)
使用标准绑定停止。
return templateFunctionTwo( &printThis, &printThat );
上面的代码中每次使用它都会使您的代码不太清晰,更容易出错。
这也是一团糟:
&templateFunctionOne< typename std::remove_reference<Fn1>::type,
typename std::remove_reference<Fn2>::type >,
std::forward<Fn1>(fn1),
std::forward<Fn2>(fn2)
为什么不
[fn1=std::forward<Fn1>(fn1),fn2=std::forward<Fn2>(fn2)]()mutable{ templateFunctionOne(std::move(fn1), std::move(fn2)); }