mercredi 29 juillet 2020

How to make a hierarchy of different object "generators" in plain C++11

What I need is the following hierarchy of classes (given here as a sketch):

class DataClass {}

class AbstractGenerator {
public:
    // Generates DataClass objects one by one. In a lazy manner
    virtual DataClass produce() = 0;
}

class RandGenerator : AbstractGenerator {
public:
    RandGenerator(int maximal_int) : maximal(maximal_int) {}
    DataClass produce() {
        // get a random number from 0 to this->maximal
        // make a DataClass object from the random int and return it
    }

private:
    int maximal;
}

class FromFileGenerator : AbstractGenerator {
public:
    FromFileGenerator(string file_name) : f_name(file_name) {}
    DataClass produce() {
        // read the next line from the file
        // deserialize the DataClass object from the line and return it
    }

private:
    string f_name;
}

What I want to support for both RandGenerator and FromFileGnerator is:

RandGenerator rg();
for (DataClass data : rg) {...}

And also some method of taking "first n elements of the generator".

What are the appropriate tools in the plain C++11 that one could use to achieve this, or whatever is the closest to this in C++11?

Aucun commentaire:

Enregistrer un commentaire