|
Boost Users : |
Subject: [Boost-users] Closures emulation made easy
From: Alexander Gutenev (gutenev_at_[hidden])
Date: 2008-09-05 04:43:35
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));
}
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net