2 ms·
> For “function objects”, closures may be more than just a nice syntax for it. Not in any language I've used. I'm not sure what language you've used but in C++
by IshKebab 4y ago
> For “function objects”, closures may be more than just a nice syntax for it.
Not in any language I've used. I'm not sure what language you've used but in C++ you would have written:
int x;
const auto getx = [&]() { return x; };
x = 5;
getx(); // 5
But that's exactly the same as this:
int x;
struct GetxFunctionObject {
int& x;
int operator()() { return x; }
};
const auto getx = GetxFunctionObject { x };
getx(); // 5
(Something like that anyway; it's been a while since I wrote C++)
- magicalhippo 4y agoIn Delphi, closures are implemented pretty much exactly as your second variant. They're implemented using a compiler-generated class. A difference is that you can't specify capture type, all captured variables are stored as fields in the class, and any outer references (such as x here) are replaced to use the field in the instance: struct GetxFunctionObject { int x; int operator()() { return x; } }; const auto getx = GetxFunctionObject(); getx.x = 5; // compiler automatically changes "x = 5" to this getx(); // 5 Modulo any it's-too-early-in-the-morning-to-write-C++ mistakes I made. I can't recall the details if multiple closures captures the same variable, might be the "obvious" solution of a shared data-class instance.