Skip to content

Instantly share code, notes, and snippets.

@lshort
Created May 24, 2014 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lshort/abef04c70b1eac55a31e to your computer and use it in GitHub Desktop.
Save lshort/abef04c70b1eac55a31e to your computer and use it in GitHub Desktop.
A template conundrum
#include <string>
#include <iostream>
#include <functional>
using std::cout;
using std::endl;
template<typename return_type, typename ...params>
auto _L( return_type (*fp) (params... args))
{ return [fp] (params... args) { return fp(args...); }; };
template<typename return_type, typename argument_type>
auto _LL( return_type (*fp) (argument_type) )
{ return [fp] (argument_type x) { return fp(x); }; };
template<typename return_type, typename arg1_type, typename arg2_type>
auto _LL( return_type (*fp) (arg1_type, arg2_type) )
{ return [=] (arg1_type x)
{ return [=] (arg2_type y) { return fp(x,y); }; };
};
int sub1(int x) { return x-1; }
double div(double x, double y) { return x/y; }
int main()
{
// bar and baz both work as expected
//
auto bar = _L(sub1);
cout << bar(1) << endl; // prints 0
auto baz = _LL(sub1);
cout << baz(1) << endl; // prints 0
// foo and doof both fail, with error
// couldn't infer template argument 'return_type'
auto foo = _L(div);
cout << foo(4.0,3.0) << endl;
auto doof = _LL(div);
cout << doof(11.0)(10.0) << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment