Skip to content

Instantly share code, notes, and snippets.

@lshort
lshort / Parking Lot
Last active January 3, 2016 07:09
A bit of code I wrote to get back up to speed on C++
using namespace std;
using boost::optional;
// Implements a parking lot utility: you can ask it for an available space for
// a car of a certain size, ask it to find a car's parking spot given its license
// plate, ask what car is parked in a specific spot, etc.
// This code is organized top down: first the parking_lot class, then
// the distance class ('dist') and some functions to compare IEEE doubles, then
// the structs 'car' and 'parking_space'. I made some assumptions, like that each
@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 (...) {