Skip to content

Instantly share code, notes, and snippets.

@nelhage
Created February 4, 2012 19:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nelhage/1739548 to your computer and use it in GitHub Desktop.
Save nelhage/1739548 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include "fluid-let.h"
int x = 1;
struct pair {
int a, b;
};
void print_x(void) {
printf("x = %d\n", x);
}
int main(void) {
print_x();
{
fluid_let(x);
x = 2;
print_x();
x = 3;
print_x();
}
print_x();
struct pair p = {0,1};
{
fluid_let(p.a) = 4;
fluid_let(p.b) = 7;
printf("p.a = %d\n", p.a);
printf("p.b = %d\n", p.b);
}
printf("p.a = %d\n", p.a);
}
template <class T>
class dynamic_binding {
public:
dynamic_binding(T& ref) : ref_(ref), orig(ref) {
}
~dynamic_binding() {
ref_ = orig;
}
const T& operator=(const T& rhs) {
ref_ = rhs;
return ref_;
}
private:
T& ref_;
T orig;
};
#define UNIQ__(token, lno) token##lno
#define UNIQ_(token, lno) UNIQ__(token, lno)
#define UNIQ(token) UNIQ_(token, __LINE__)
#define fluid_let(x) dynamic_binding<typeof(x)> UNIQ(_dynamic)(x); UNIQ(_dynamic)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment