C ++绑定函数用作其他函数的参数 [英] C++ bind function for use as argument of other function

查看:95
本文介绍了C ++绑定函数用作其他函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,需要函数指针作为参数:

I have a function that requires a function pointer as argument:

int func(int a, int (*b)(int, int))
{
    return b(a,1);
}

现在,我想在此函数中使用具有三个参数的某个函数:

Now I want to use a certain function that has three arguments in this function:

int c(int, int, int)
{
    // ...
}

如何绑定c的第一个参数,以便能够执行此操作:

How can I bind the first argument of c so that I'm able to do:

int i = func(10, c_bound);

我一直在查看std::bind1st,但似乎无法弄清楚.它不返回函数指针吗?我有充分的自由来适应func,因此方法的任何更改都是可能的. Althoug我希望代码的用户能够定义自己的c ...

I've been looking at std::bind1st but I cannot seem to figure it out. It doesn't return a function pointer right? I have full freedom to adapt func so any changes of approach are possible. Althoug I would like for the user of my code to be able to define their own c...

请注意,以上内容是我正在使用的实际功能的极大简化.

note that the above is a ferocious simplification of the actual functions I'm using.

可悲的是,该项目需要C++98.

The project sadly requires C++98.

推荐答案

您不能这样做.您必须修改func才能首先使用功能对象.像这样:

You can't do that. You would have to modify func to take a function-object first. Something like:

int func( int a, std::function< int(int, int) > b )
{
    return b( a, rand() );
}

实际上,不需要bstd::function,可以将其模板化:

In fact, there is no need for b to be an std::function, it could be templated instead:

template< typename T >
int func( int a, T b )
{
    return b( a, rand() );
}

但是为了清晰起见,我会坚持使用std::function版本,并且在出错时编译器输出会有些混乱.

but I would stick with the std::function version for clarity and somewhat less convoluted compiler output on errors.

然后您将可以执行以下操作:

Then you would be able to do something like:

int i = func( 10, std::bind( &c, _1, _2, some-value ) );

请注意,所有这些都是 C ++ 11 ,但是您可以使用Boost在 C ++ 03 中完成.

Note all this is C++11, but you can do it in C++03 using Boost.

这篇关于C ++绑定函数用作其他函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆