编辑:我使用下面咖喱,但被告知这是代替部分应用程序。
我一直在试图找出一个如何编写C ++咖喱功能,实际上我理解了它!
#include <stdio.h>
#include <functional>
template< class Ret, class Arg1, class ...Args >
auto curry( Ret f(Arg1,Args...), Arg1 arg )
-> std::function< Ret(Args...) >
{
return [=]( Args ...args ) { return f( arg, args... ); };
}
我写的lambda表达式的一个版本了。
template< class Ret, class Arg1, class ...Args >
auto curry( const std::function<Ret(Arg1,Args...)>& f, Arg1 arg )
-> std::function< Ret(Args...) >
{
return [=]( Args ...args ) { return f( arg, args... ); };
}
测试:
int f( int x, int y )
{
return x + y;
}
int main()
{
auto f5 = curry( f, 5 );
auto g2 = curry( std::function<int(int,int)>([](int x, int y){ return x*y; }), 2 );
printf("%d\n",f5(3));
printf("%d\n",g2(3));
}
呸! 行初始化G2是如此之大,我还不如手动咖喱它。
auto g2 = [](int y){ return 2*y; };
矮得多。 但由于目的是有一个非常通用的和方便的咖喱功能,可我是(1)写出更好的功能或(2)不知我的拉姆达隐式构造的std ::功能? 我担心目前的版本至少违反惊喜的规则时,f是不是免费的功能。 尤其可气的是没有make_function或相似类型的功能,我知道怎么的,似乎存在。 说真的,我的理想的解决办法只是到std ::绑定的电话,但我不知道如何使用可变参数模板使用。
PS:不提升,请,但我会解决,如果没有别的。
编辑:我已经知道的std ::绑定。 如果标准::绑定做了什么我想最好的语法我不会写这个功能。 这应该是更多的在那里只是结合的第一个元素的一个特例。
正如我所说的,我的理想的解决方案应该使用绑定,但如果我想清楚了,我会利用这一点。
Answer 1:
您的curry
功能只是一个按比例缩小的低效子情况std::bind
( std::bind1st
和bind2nd
不应该再现在我们使用std::result_of
)
你的两行读事实上
auto f5 = std::bind(f, 5, _1);
auto g2 = std::bind(std::multiplies<int>(), 2, _1);
其使用后的namespace std::placeholders
。 这避免了仔细的拳击进入std::function
和允许编译器在调用点更容易的结果内联。
对于两个参数的功能,黑客像
auto bind1st(F&& f, T&& t)
-> decltype(std::bind(std::forward<F>(f), std::forward<T>(t), _1))
{
return std::bind(std::forward<F>(f), std::forward<T>(t), _1)
}
可以工作,但它是很难一概而论的可变参数情况下(这你最终改写了很多的逻辑std::bind
)。
也讨好不是局部应用。 柯里有“签名”
((a, b) -> c) -> (a -> b -> c)
即。 它是把一个函数接受两个参数到返回功能的功能作用。 它的逆uncurry
执行反向操作(数学家: curry
和uncurry
是同构,并定义一个红利)。 这个逆是非常麻烦的在C ++写(提示:使用std::result_of
)。
Answer 2:
这是一种能够在C ++讨好,可能是也可能不是最近编辑在OP后相关。
由于超载是非常有问题的检查一个仿函数,并检测其元数。 什么是可能的不过是给出一个仿函数f
和一个参数a
,我们可以检查,如果f(a)
是有效的表达式。 如果不是,我们可以存储a
,并给予下列参数b
,我们可以检查,如果f(a, b)
是一个有效的表达,等等。 以机智:
#include <utility>
#include <tuple>
/* Two SFINAE utilities */
template<typename>
struct void_ { using type = void; };
template<typename T>
using Void = typename void_<T>::type;
// std::result_of doesn't play well with SFINAE so we deliberately avoid it
// and roll our own
// For the sake of simplicity this result_of does not compute the same type
// as std::result_of (e.g. pointer to members)
template<typename Sig, typename Sfinae = void>
struct result_of {};
template<typename Functor, typename... Args>
struct result_of<
Functor(Args...)
, Void<decltype( std::declval<Functor>()(std::declval<Args>()...) )>
> {
using type = decltype( std::declval<Functor>()(std::declval<Args>()...) );
};
template<typename Functor, typename... Args>
using ResultOf = typename result_of<Sig>::type;
template<typename Functor, typename... Args>
class curry_type {
using tuple_type = std::tuple<Args...>;
public:
curry_type(Functor functor, tuple_type args)
: functor(std::forward<Functor>(functor))
, args(std::move(args))
{}
// Same policy as the wrappers from std::bind & others:
// the functor inherits the cv-qualifiers from the wrapper
// you might want to improve on that and inherit ref-qualifiers, too
template<typename Arg>
ResultOf<Functor&(Args..., Arg)>
operator()(Arg&& arg)
{
return invoke(functor, std::tuple_cat(std::move(args), std::forward_as_tuple(std::forward<Arg>(arg))));
}
// Implementation omitted for brevity -- same as above in any case
template<typename Arg>
ResultOf<Functor const&(Args..., Arg)>
operator()(Arg&& arg) const;
// Additional cv-qualified overloads omitted for brevity
// Fallback: keep calm and curry on
// the last ellipsis (...) means that this is a C-style vararg function
// this is a trick to make this overload (and others like it) least
// preferred when it comes to overload resolution
// the Rest pack is here to make for better diagnostics if a user erroenously
// attempts e.g. curry(f)(2, 3) instead of perhaps curry(f)(2)(3)
// note that it is possible to provide the same functionality without this hack
// (which I have no idea is actually permitted, all things considered)
// but requires further facilities (e.g. an is_callable trait)
template<typename Arg, typename... Rest>
curry_type<Functor, Args..., Arg>
operator()(Arg&& arg, Rest const&..., ...)
{
static_assert( sizeof...(Rest) == 0
, "Wrong usage: only pass up to one argument to a curried functor" );
return { std::forward<Functor>(functor), std::tuple_cat(std::move(args), std::forward_as_tuple(std::forward<Arg>(arg))) };
}
// Again, additional overloads omitted
// This is actually not part of the currying functionality
// but is here so that curry(f)() is equivalent of f() iff
// f has a nullary overload
template<typename F = Functor>
ResultOf<F&(Args...)>
operator()()
{
// This check if for sanity -- if I got it right no user can trigger it
// It *is* possible to emit a nice warning if a user attempts
// e.g. curry(f)(4)() but requires further overloads and SFINAE --
// left as an exercise to the reader
static_assert( sizeof...(Args) == 0, "How did you do that?" );
return invoke(functor, std::move(args));
}
// Additional cv-qualified overloads for the nullary case omitted for brevity
private:
Functor functor;
mutable tuple_type args;
template<typename F, typename Tuple, int... Indices>
ResultOf<F(typename std::tuple_element<Indices, Tuple>::type...)>
static invoke(F&& f, Tuple&& tuple, indices<Indices...>)
{
using std::get;
return std::forward<F>(f)(get<Indices>(std::forward<Tuple>(tuple))...);
}
template<typename F, typename Tuple>
static auto invoke(F&& f, Tuple&& tuple)
-> decltype( invoke(std::declval<F>(), std::declval<Tuple>(), indices_for<Tuple>()) )
{
return invoke(std::forward<F>(f), std::forward<Tuple>(tuple), indices_for<Tuple>());
}
};
template<typename Functor>
curry_type<Functor> curry(Functor&& functor)
{ return { std::forward<Functor>(functor), {} }; }
上面的代码编译使用GCC 4.8快照(禁止拷贝和粘贴错误),条件是在一个indices
型和indices_for
效用。 这个问题和它的答案表明,有必要和实施这样的事情,其中seq
扮演的角色indices
和gens
可以用来实现一个(更方便) indices_for
。
非常仔细地在上面,当涉及到价值范畴和(可能)的临时寿命。 curry
(和与之配套的类型,这是一个实现细节)被设计为尽可能轻巧,同时还使得它非常,非常安全的使用。 特别地,使用如:
foo a;
bar b;
auto f = [](foo a, bar b, baz c, int) { return quux(a, b, c); };
auto curried = curry(f);
auto pass = curried(a);
auto some = pass(b);
auto parameters = some(baz {});
auto result = parameters(0);
不复制f
, a
或b
; 也不会导致悬挂引用临时对象。 这一切都仍然适用,即使auto
取代有auto&&
(假设quux
是理智的,但是这是无法控制的curry
)。 它仍然能够拿出在这方面不同的策略(如系统地衰减)。
需要注意的是参数(但不是仿函数)与在最后调用相同的价值范畴时,他们传递给咖喱包装为通过。 因此,在
auto functor = curry([](foo f, int) {});
auto curried = functor(foo {});
auto r0 = curried(0);
auto r1 = curried(1);
这意味着一个移动-从foo
被计算时传递到底层函子r1
。
Answer 3:
随着一些C ++ 14点的特性,部分应用程序对拉姆达的可以在一个非常简洁的方式来实现的作品。
template<typename _function, typename _val>
auto partial( _function foo, _val v )
{
return
[foo, v](auto... rest)
{
return foo(v, rest...);
};
}
template< typename _function, typename _val1, typename... _valrest >
auto partial( _function foo, _val1 val, _valrest... valr )
{
return
[foo,val,valr...](auto... frest)
{
return partial(partial(foo, val), valr...)(frest...);
};
}
// partial application on lambda
int p1 = partial([](int i, int j){ return i-j; }, 6)(2);
int p2 = partial([](int i, int j){ return i-j; }, 6, 2)();
Answer 4:
很多例子的人提供,我看到其他地方使用的辅助类做任何他们做到了。 我意识到这一点变得微不足道当你这样做来写!
#include <utility> // for declval
#include <array>
#include <cstdio>
using namespace std;
template< class F, class Arg >
struct PartialApplication
{
F f;
Arg arg;
constexpr PartialApplication( F&& f, Arg&& arg )
: f(forward<F>(f)), arg(forward<Arg>(arg))
{
}
/*
* The return type of F only gets deduced based on the number of arguments
* supplied. PartialApplication otherwise has no idea whether f takes 1 or 10 args.
*/
template< class ... Args >
constexpr auto operator() ( Args&& ...args )
-> decltype( f(arg,declval<Args>()...) )
{
return f( arg, forward<Args>(args)... );
}
};
template< class F, class A >
constexpr PartialApplication<F,A> partial( F&& f, A&& a )
{
return PartialApplication<F,A>( forward<F>(f), forward<A>(a) );
}
/* Recursively apply for multiple arguments. */
template< class F, class A, class B >
constexpr auto partial( F&& f, A&& a, B&& b )
-> decltype( partial(partial(declval<F>(),declval<A>()),
declval<B>()) )
{
return partial( partial(forward<F>(f),forward<A>(a)), forward<B>(b) );
}
/* Allow n-ary application. */
template< class F, class A, class B, class ...C >
constexpr auto partial( F&& f, A&& a, B&& b, C&& ...c )
-> decltype( partial(partial(declval<F>(),declval<A>()),
declval<B>(),declval<C>()...) )
{
return partial( partial(forward<F>(f),forward<A>(a)),
forward<B>(b), forward<C>(c)... );
}
int times(int x,int y) { return x*y; }
int main()
{
printf( "5 * 2 = %d\n", partial(times,5)(2) );
printf( "5 * 2 = %d\n", partial(times,5,2)() );
}
文章来源: Partial application with a C++ lambda?