4 ms·
Why would you do something like this rather than just using function objects for your generators? class FunctionObject { //internal state as member
by Figs 16y ago
Why would you do something like this rather than just using function objects for your generators?
class FunctionObject {
//internal state as member variables
public:
FunctionObject() { /* ... */ }
returnType operator()() { /* Calculate next step */ }
};
- comex 16y agoBecause keeping the internal state implicitly (in loops, etc) can make the code much cleaner. See, e.g., http://wiki.python.org/moin/Generators http://wiki.python.org/moin/Generators
- scott_s 16y agoWhile it may look cleaner on the surface, I don't think this sort of hackery actually is cleaner. Are you certain this solution will work with multiple threads? What if a signal is received during one of these calls? Are you sure it will work across all architectures? Operating systems? I prefer to stay within a language's semantics if possible; it reduces these sorts of concerns. For C++, that would mean using function objects.
- Figs 16y agoHis code is also non-portable, and non-standard. I haven't been able to get it to compile on my system yet, but I don't see anywhere that he's capturing the variables on the stack, so while you may be able to jump back to your position after one call, you'll loose whatever parameters you passed (assuming you don't simply crash). Also, since it seems to depend on a static variable hidden within the function, I doubt it will work even in single threaded programs if you need multiple generators. This is just my five minute analysis though, so grain of salt and all that.
- scott_s 16y agoAs I noted below, you can solve the stack problem with setjmp() and longjmp(). But that's only portable across different Unixes, not across all systems which will have C++. But, yes, I am in agreement: function objects are the better solution to this problem in C++. This sort of hackery, while neat, leads to a rats nest of problems.
- zeen 16y agoThe code provided isn't storing any internal state (aside from the resume location) as far as I can see. The generator thus generated isn't reentrant and has other flaws, but those pale to nothing when you consider that nothing on the stack is preserved..