Closures emulation made easy
Hi. Here's a trick. Use the idea of Boost.ScopeExit. But don't implement capturing of variables like in Boost.ScopeExit - use Boost.Bind which does it. Have easy to write and debug closure body - don't spend too much time on making Boost.Lamda work. And a compact implementation with very small proprocessor overhead, compared to Boost.ScopeExit. // Implementation #define CONCATENATE_DIRECT(s1, s2) s1##s2 #define CONCATENATE(s1, s2) CONCATENATE_DIRECT(s1, s2) #define ANONYMOUS_VARIABLE(str) CONCATENATE(str, __LINE__) #define LOCAL(R, P) \ typedef struct ANONYMOUS_VARIABLE(xg1) { \ typedef R(*F) P; static R body P { #define LOCAL_END(name) \ } } ANONYMOUS_VARIABLE(xg2); \ const ANONYMOUS_VARIABLE(xg2)::F name \ = ANONYMOUS_VARIABLE(xg2)::body; // Example #include <algorithm> int main() { LOCAL(bool, (int i, int j, bool reverse)) return reverse ? (j < i) : (i < j); LOCAL_END(myFcn) int a[] = { 2, 5, 1, 6 }; std::sort( a, a + sizeof(a)/sizeof(a[0]), boost::bind(myFcn, _1, _2, true)); }
Steven Watanabe wrote in message news:48C1500E.4060500@providere-consulting.com...
What is the advantage over defining a function at namespace scope?
1. Have it close to the resource acquisition, not 50 lines away. 2. Encapsulation, exactly not having any extra stuff in a namespace.
participants (2)
-
Alexander Gutenev
-
Steven Watanabe