我想创建这样的值:(我必须使用以下语法)。因此目标是通过STL函数generate_n和函数类“Sequencegenerator”创建值,该函数是模板函数。我的问题是,我不知道如何返回值以及如何将其保存到下一个调用。下来有我的代码...非常感谢你! (我必须在不使用operator()
的情况下解决它// Numbers from 1 to 10
generate_n(ostream_iterator<int>(cout, " "), 10, SequenceGenerator<int>(1));
cout << endl;
// Numbers from 10 to 1 (descending order)
generate_n(ostream_iterator<int>(cout, " "), 10, SequenceGenerator<int>(10, -1));
cout << endl;
// Numbers from 0 to 5 (increment 0.5)
generate_n(ostream_iterator<double>(cout, " "), 11, SequenceGenerator<double>(0, 0.5));
cout << endl;
// Letters from A to Z
generate_n(ostream_iterator<char>(cout, ""), 26, SequenceGenerator<char>(’A’));
cout << endl;
我的代码:
#include <algorithm>
#include <iterator>
#include <iostream>
#include "SequenceGenerator.h"
using namespace std;
template <typename T>
class SequenceGenerator : public std::unary_function<T,T>
{
public:
SequenceGenerator(T const start, T const inc):mStart(start),mInc(inc)
{
return mStart = mStart + inc;
}
private:
T const mInc;
static T mStart; //static T mStart
};
int main()
{
generate_n(ostream_iterator<int>(cout, " "), 10, SequenceGenerator<int>(10,1) );
return 0;
}
答案 0 :(得分:2)
您无法在此处避免operator ()
,因为这是std::generate_n
函数调用SequenceGenerator
模板实例的内容。
可行的模板实现如下:
template <typename T>
class SequenceGenerator
: public std::unary_function<T,T> // This is superfluous for this usage
{
public:
SequenceGenerator(T const start, T const inc = 1)
: mStart (start)
, mInc (inc)
{
}
T operator () ()
{
T ret = mStart;
mStart += mInc;
return ret;
}
private:
T const mInc;
T mStart;
};