Adding a Python style yield to C++
flipcode.com
flipcode.com
class FunctionObject {
//internal state as member variables
public:
FunctionObject() { /* ... */ }
returnType operator()() { /* Calculate next step */ }
};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.
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.
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.
First, it seems like they would be easier to write in C++. You're mostly creating a new kind of pseudo-container (channel), instead of trying to fake adding new syntax to the language. (Although you do still need to have some mechanism for executing a go routine, somehow ....)
Second, its a more powerful abstraction. With go routines it's not hard to implement something with the functionality of Python-esque generators, but you can also do fancier things that you would have a difficult time doing using only generators.
Not to diminish the author, who probably has good potential, but I don't think this article is really of HN quality.