在C函数组成++ [英] Function Composition in C++
问题描述
有很多IM pressive Boost库如Boost.Lambda或Boost.Phoenix这对于使C ++成为一个真正的函数式语言很长的路要走的。但是,有没有创造任何2个或多个任意函数或仿函数的复合函数的简单方法?
There are a lot of impressive Boost libraries such as Boost.Lambda or Boost.Phoenix which go a long way towards making C++ into a truly functional language. But is there a straightforward way to create a composite function from any 2 or more arbitrary functions or functors?
如果我有: INT F(INT X)
和 INT克(INT X)
,我想做这样的事情 F。摹
这将静态生成一个新的函数对象等同于 F(克(X))。
If I have: int f(int x)
and int g(int x)
, I want to do something like f . g
which would statically generate a new function object equivalent to f(g(x)).
此似乎通过各种技术,如那些此处讨论成为可能。当然,你可以连锁调用的boost ::拉姆达::绑定
来创建一个复合仿函数。但是,有没有在任何升压这容易让你采取任何两个或多个函数或函数对象,并结合他们创造一个单一的复合仿函数,类似于你会怎么做它象Haskell语言?
This seems to be possible through various techniques, such as those discussed here. Certainly, you can chain calls to boost::lambda::bind
to create a composite functor. But is there anything in Boost which easily allows you to take any 2 or more functions or function objects and combine them to create a single composite functor, similar to how you would do it in a language like Haskell?
推荐答案
我不知道的东西都支持你希望目前的语法。然而,这将是一个简单的事情来创建一个。简单地覆盖*为仿函数(升压::功能<>为例)。因此,它返回一个复合仿
I don't know of anything that supports the syntax you wish for currently. However, it would be a simple matter to create one. Simply override * for functors (boost::function<> for example) so that it returns a composite functor.
template < typename R1, typename R2, typename T1, typename T2 >
boost::function<R1(T2)> operator * (boost::function<R1(T2)> const& f, boost::function<R2(T2)> const& g)
{
return boost::bind(f, boost::bind(g, _1));
}
未经检验的,但我怀疑它很接近,如果它不开箱的工作。
Untested, but I suspect it's close if it doesn't work out of the box.
这篇关于在C函数组成++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!