EDIT: I use curry below, but have been informed this is instead partial application.
I\'ve been trying to figure out how one would write a curry function in C++, and i a
A lot of the examples people provided and that i saw elsewhere used helper classes to do whatever they did. I realized this becomes trivial to write when you do that!
#include // for declval
#include
#include
using namespace std;
template< class F, class Arg >
struct PartialApplication
{
F f;
Arg arg;
constexpr PartialApplication( F&& f, Arg&& arg )
: f(forward(f)), arg(forward(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()...) )
{
return f( arg, forward(args)... );
}
};
template< class F, class A >
constexpr PartialApplication partial( F&& f, A&& a )
{
return PartialApplication( forward(f), forward(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(),declval()),
declval()) )
{
return partial( partial(forward(f),forward(a)), forward(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(),declval()),
declval(),declval()...) )
{
return partial( partial(forward(f),forward(a)),
forward(b), forward(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)() );
}