如何使不同对象“生成器"的层次结构成为可能.在纯C ++ 11中 [英] How to make a hierarchy of different object "generators" in plain C++11
本文介绍了如何使不同对象“生成器"的层次结构成为可能.在纯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;
}
我想同时支持 RandGenerator
和 FromFileGnerator
的是:
RandGenerator rg();
for (DataClass data : rg) {...}
还有一些获取生成器的前n个元素"的方法.
And also some method of taking "first n elements of the generator".
在普通的C ++ 11中,可以使用哪些合适的工具来实现此目的,或者在C ++ 11中最接近的工具是什么?
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?
推荐答案
boost::function_input_iterator
is the normal tool for this job, but since you want "plain" C++, we can just reimplement the same concept.
class generator_iterator {
std::shared_ptr<AbstractGenerator> generator;
public:
using iterator_category = std::input_iterator_tag;
generator_iterator(std::shared_ptr<AbstractGenerator> generator_)
:generator(generator_) {}
DataClass operator*(){return generator->produce();}
generator_iterator& operator++(){return *this;}
generator_iterator operator++(int){return *this;}
//plus all the other normal bits for an output_iterator
};
然后在您的 AbstractGenerator
类中,提供 begin
和 end
方法.
And then in your AbstractGenerator
class, provide begin
and end
methods.
generator_iterator begin() {return {this};}
generator_iterator end() {return {nullptr};} //or other logic depending on how you want to detect the end of a series
这篇关于如何使不同对象“生成器"的层次结构成为可能.在纯C ++ 11中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文