Philipp Doublehammer
Philipp Doublehammer

Reputation: 332

How to return a value without a function call?

I want to create values like this: (i have to use the following syntax). So the target is to create values by the STL-function generate_n and an functor-class "Sequencegenerator" which is a template function. My problem is, i don't know how to return the value and how to save it to the next call. Down there is my code... thank you a lot! (I have to solve it without using the 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;

MY CODE:

#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;
}

Upvotes: 0

Views: 161

Answers (1)

yzt
yzt

Reputation: 9103

You cannot avoid operator () here, because that's what the std::generate_n function calls on instances of your SequenceGenerator template.

An implementation of the template that will work looks like this:

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;
};

Upvotes: 2

Related Questions