Это то, что вы преследовали?
Я не совсем уверен, что вы хотели, чтобы generator
вернул, но, пожалуйста, измените, как хотите.
Идея состоит в том, что объект генератора сохраняет свое собственное состояние, и когда вы вызываете метод для него, он возвращает вам следующее значение. Это полностью зависит от вас, что вы определяете как состояние и следующее значение, которое будет возвращено.
operator()
может принимать параметры, как в operator()(bool b
) или operator()(char * c)
, а также возвращать любое желаемое значение ...
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct generator
{
generator() : currentCh(0), currentW(0), str(0), words()
{ // do whatever initialization you need
words.push_back("Foobar");
words.push_back("Barfoo");
str = &words[currentW];
}
char operator()()
{ // use whatever logic you need
if (currentCh >= str->size())
{
if (++currentW >= words.size()) currentW = 0;
str = &words[currentW];
currentCh = 0;
}
return str->at(currentCh++);
}
unsigned int currentCh;
unsigned int currentW;
string * str;
vector<string> words;
};
Вы можете обновлять внутренние состояния по своему усмотрению, например, добавить:
char operator()(unsigned int index)
{
currentCh = index;
return this->operator()();
}
Тогда в вашем коде где-то вы можете сделать:
generator g;
g(); // get first character
g(2); // resets the index in this case ...
g(); // get next character (the logic is a bit off but it depends what you need)
Использование:
int main()
{
generator g;
for (unsigned int i = 30; --i; ) cout << g() << endl;
}
Выход:
F
o
o
b
a
r
B
a
r
f
o
o
F
o
o
b
a
r
B
a
r
f
o
o
F
o
o
b
a