Reputation:
I want to know how to implement a generator , like Python, in C++? Python can use keyword "yield" to do so. But how to do it in C++?
Upvotes: 17
Views: 10328
Reputation: 5369
Calling a coroutine multiple times and getting different answers means you keep some state. The way to keep a state is objects. The way to make them look like function call is operator overloading. For some examples see the function object article in Wikipedia.
Upvotes: 3
Reputation: 41509
To elaborate on the iterator implementation: this is an example. It can be used as a loop variable, or in std algorithms.
#include <iterator>
template< typename T, typename TDiff = T >
struct TGenerator : public std::iterator<std::forward_iterator_tag,T,TDiff> {
T from,to;
T value;
TDiff step;
bool issentinel;
TGenerator( T from, T to, TDiff step, bool sentinel = false )
: from(from),to(to),step(step),issentinel(sentinel), value(from)
{}
void operator++(){ value += step; }
const T& operator*()const { return value; }
bool operator!=( const TGenerator& other ) const {
return value<to;
}
TGenerator sentinel()const { return TGenerator(0,0,0,true); }
};
#include <algorithm>
#include <iostream>
int main()
{
TGenerator<int> i(0,10,3);
std::copy( i, i.sentinel(), std::ostream_iterator<int>( std::cout, " " ) );
return 0;
}
Upvotes: 7
Reputation: 26953
you can use boost.context (sorry, not on boost distribution yet, you'll have to get it from boost vault).
A typical example code would be like this:
#include <iostream>
#include <boost/context.hpp>
using namespace std;
struct Parameters {
int par1;
float par2;
};
boost::context c1;
boost::context c2;
void F(void* parameters) {
Parameters& pars = *(Parameters*)parameters;
cout << pars.par1 << endl;
c2.jump_to(c1);
cout << pars.par2 << endl;
};
int main() {
c1 = boost::context::current();
Parameters p;
p.par1 = 8;
c2 = boost::context::create_context( F , c1 , p );
c1.jump_to(c2);
p.par2 = 1.3;
c1.jump_to(c2);
}
Upvotes: 1
Reputation: 47052
You can't do it, really, but you can fake it. Here's a way you can fake it in C, which you can use in C++ as well.
Upvotes: 6