-
Notifications
You must be signed in to change notification settings - Fork 0
How to write generator
Writing generator consists of the following steps:
Declare generator type
Generator type must be a class or a structure, inherited from the pseudo_generator< value_type, generator_type >.
It have 2 template parameters:
- value_type – type of the value, returned by the generator
- generator_type – the inherited type itself. (So called “Curiously Recurring Template Parameters” pattern )
The only thing, generator class must have is an overloaded method () with the sole argument of type (value_type &).
This method will contain the generator code.
Generator class can have any other methods and fields.
Writing generator code
Generator code is placed into the overloaded operator ()( value_type &value ).
There is some boilerplate code, that must be present in the any generator implementation:
=Preamble
In the very beginning, put the macro (N is some positive number ):
GENERATORN;
Arguments to this macro are names of the /states/ (see below).
=End=
At the very end of the generator, put the macro
END_GENERATOR;
Main code (generator body)=
Just write code of the generator, as you do it in the Python program, using YIELD macro to yield values.
However, YIELD macro is a bit more complicated than yield operator in python.
Macro have 3 arguments: YIELD
where:
- variable_name – name of the argument of the operator()( value_type & )
- value – yielded value
- state – name of the /state/
The /state/ is simply identifier of the YIELD. Each YIELD must have its own state name.
You can’t use same state for two different YIELDs, it would cause compilation errors.
All state names must be listed in the GENERATORN macro at the beginning of the generator code.
=Limitatoins=
There is only one serious limitation on the code of the generator body:
- No local variables must be visible, when YIELD is used.
Simpliest way to meet this limitation is not to use local variable at all, use only fields.
However, you can use local variables, if they are not visible in the YIELD scope.
For example:
void my_generator::operator()( int & value )
{
GENERATOR3( state1, state2, state3 );
int x = 10;
YIELD(
}