Skip to content

Instantly share code, notes, and snippets.

@lshort
lshort / bad_templates
Created May 24, 2014 15:02
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...); }; };
auto lambda_plus = [] (auto x, auto y) { return x+y; };
int z = lambda_plus(5,3);
auto incr = [](auto a) {return a+1;};
auto dbl = [](auto a) {return a*2;};
auto output_decorate = [](auto a) {cout<<a<<" "<<endl; return a;};
auto dbl_incr_decor = output_decorate * incr * dbl;
int x = dbl_incr_decor(5);
double y = dbl_incr_decor(.5);
auto triple = [](auto a) { return a*3; };
cout << (triple * incr *dbl)(5) << endl;
auto map = [] (const auto &function, const auto &container )
{
auto retval = container;
retval.clear();
for (const auto &elem : container)
retval.push_back(function(elem));
return retval;
};
vector<int> data {1,2,3,4};
template<typename return_type, typename ...params>
auto _L( return_type (*fp) (params... args))
{ return [fp] (params... args) { return fp(args...); }; };
auto incr = [](auto a) {return a+1;};
int add1(int x) { return x+1; }
int sub1(int x) { return x-1; }
auto ident = _L(add1) * _L(sub1);
auto ident2 = incr * _L(sub1);
cout << ident(1) << "," << ident2(1) << endl;
template<typename return_type, typename arg1_type, typename ...params>
auto _L1( return_type (*fp) (arg1_type x, params...args), arg1_type x)
{ return [fp, x] (params...args) { return fp(x,args...); }; };
double mult(double x, double y) { return x*y; }
auto to_radians = _L1(mult,M_PI/180.0);
auto cos_in_degrees = _L(cos) * to_radians;
cout << cos_in_degrees(45.0) << endl;
@lshort
lshort / ExpectExceptionBasic
Last active August 29, 2015 14:03
ExpectExceptionBasic
template<typename ExecLambda>
void expect_exception( ExecLambda exec_lambda, bool expect_to_throw)
{
bool threw;
decltype( exec_lambda() ) x;
try {
x = exec_lambda();
threw = false;
}
catch (...) {
@lshort
lshort / ImprovedExpectException
Created June 30, 2014 02:56
Improved expect_exception
template<typename ExecLambda, typename OnThrowLambda, typename NoThrowLambda>
auto expect_exception( ExecLambda exec_lambda, bool expect_to_throw,
OnThrowLambda exc_lambda, NoThrowLambda no_exc_lambda)
{
bool threw;
decltype( exec_lambda() ) x;
try {
x = exec_lambda();
threw = false;