我有一个函数,需要一个函数指针作为参数:
int func(int a, int (*b)(int, int))
{
return b(a,1);
}
Run Code Online (Sandbox Code Playgroud)
现在我想在这个函数中使用一个具有三个参数的函数:
int c(int, int, int)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
如何绑定第一个参数,c
以便我能够:
int i = func(10, c_bound);
Run Code Online (Sandbox Code Playgroud)
我一直在看,std::bind1st
但我似乎无法弄明白.它不会返回一个函数指针吗?我有充分的自由适应,func
因此任何方法的改变都是可能的.Althoug我希望我的代码用户能够定义自己的c
...
请注意,上面是我正在使用的实际功能的凶猛简化.
该项目遗憾地要求C++98
.
K-b*_*llo 12
你不能这样做.您必须先修改func
以获取函数对象.就像是:
int func( int a, std::function< int(int, int) > b )
{
return b( a, rand() );
}
Run Code Online (Sandbox Code Playgroud)
事实上,没有必要b
成为一个std::function
,它可能是模板化的:
template< typename T >
int func( int a, T b )
{
return b( a, rand() );
}
Run Code Online (Sandbox Code Playgroud)
但std::function
为了清晰起见,我会坚持使用该版本,并且在错误方面,编译器输出稍微复杂一些.
然后你就可以做类似的事情:
int i = func( 10, std::bind( &c, _1, _2, some-value ) );
Run Code Online (Sandbox Code Playgroud)
注意这一切都是C++ 11,但你可以使用Boost 在C++ 03中完成.