如何将一个函数绑定到另一个函数
我有一个函数 A
,它接受谓词函数作为其参数。
我有另一个函数 B
,它接受一个 char
并返回一个 int
,以及一个接受 C
的函数code>int 并返回一个 bool
。
我的问题是如何绑定 B
和 C
将其传递给函数 A
。
比如:
A(bindfunc(B,C))
我知道 boost::bind
有效,但我正在寻找 STL 解决方案。
例如,
int count(vector<int> a, pred func); // A
//this functions counts all elements which satisfy a condition
int lastdigit(int x); // B
//this function outputs last digit(in decimal notation) of number x
bool isodd(int x); // C
//this function tells if number x is odd
// i want to find the count of all such numbers in a vector whose last digit is odd
// so i want something like
count(vector<int> a, bind(lastdigit, isodd))
一种不好的方法是创建一个显式执行绑定操作的冗余函数D
。
I have a function A
that accepts a predicate function as its argument.
I have another function B
and it takes a char
and returns an int
, and a function C
that accepts int
and returns a bool
.
My question is how to bind B
and C
to pass it to function A
.
Something like:
A(bindfunc(B,C))
I know boost::bind
works but i am looking for STL solution.
For example,
int count(vector<int> a, pred func); // A
//this functions counts all elements which satisfy a condition
int lastdigit(int x); // B
//this function outputs last digit(in decimal notation) of number x
bool isodd(int x); // C
//this function tells if number x is odd
// i want to find the count of all such numbers in a vector whose last digit is odd
// so i want something like
count(vector<int> a, bind(lastdigit, isodd))
One bad way would be to make a redundant function D
which explicitly performs bind operation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为
std
中缺少compose
高阶函数的简单解决方法:请注意,它不适用于二进制函数(涉及更多工作),并且您的函数必须是 STL 函数对象。这意味着如果您有函数指针,则必须用 std::ptr_fun 包装它们。
As a simple workaround for the lack of a
compose
higher order function instd
:Note that it doesn't work for binary functions (more work is involved), and that your functions must be STL function objects. It means that if you have function pointers, you must wrap them with
std::ptr_fun
.我认为 STL 的绑定函数不够通用,无法满足您的需求。
I don't believe that the STL's bind functions are general enough for your needs.