C++ has `local'!
Not exactly Perl post, but very related!
I wanted to add the `local' feature to C++ and this is how i did it:
The code:
#include <iostream>
#include <string>using namespace std;
template<class T>
struct clocal {
clocal(T& p) : pvar(p), pval(p) {}
clocal& operator=(const T& val) { pvar=val; return *this; }
~clocal() { pvar=pval; }
T& pvar;
T pval;
};string s = "global";
int i = 0;void print()
{
cout << s << ", " << i << endl;
}#define local(var) clocal<typeof var> clocal_ ## var ## \
_ ## __LINE__(var); clocal_ ## var ## _ ## __LINE__int main()
{
print();
for (char c='1'; c<'3'; ++c) {
local(s) = string("local") + c;
local(i) = 1000 + c - '0';
print();
}
print();
}
Output:
global, 0 local1, 1001 local2, 1002 global, 0
Leave a comment