Boost logo

Boost :

From: Richard Peters (R.A.Peters_at_[hidden])
Date: 2002-06-11 03:10:57


Small detail: the test could could test what the value of x++ is, like this:
    cout << "Before x = " << x << endl;
    cout << "In between x = " << x++ << endl;
    cout << "After x = " << x << endl;
It works correctly. (output is 1, 1, 2)

The helper class could be made a seperate class with a helper function, like this:

    template<class T>
    struct postfix_incrementer: public T
    {
        postfix_incrementer(T &rhs): T(rhs) // call the copy constructor!
        {
            ++rhs;
        }
    };

    template<class T>
    T postfix_increment(T& rhs)
    {
        return postfix_incrementer<T>(rhs);
    }

Then you can replace the postfix increment operator with

    number operator++(int)
    { return postfix_increment(*this); }

The only thing is that I do not clearly see if there's still the copying
advantage...
Is this useful for the utility library?

Richard Peters

----- Original Message -----
From: "Powell, Gary" <powellg_at_[hidden]>

> Ah but you can fix the need to call the copy constructor by using a
> helper template class instead.
> (I credit this to Joel's suggestion!)
>
> -Gary-
>
> PS
> Of course if this doesn't really work, I'm to blame.
> -----------------------------------------------
>
> class number {
> private:
>
> template<class T>
> struct helper_class : public T
> {
> helper_class(T &rhs): T(rhs) // call the copy constructor!
> {
> ++rhs;
> }
> };
>
> int value;
>
> public:
> explicit number(int rhs = 0)
> : value(rhs) {}
>
> number &operator++()
> { ++value; return *this; }
>
> number operator++(int)
> { return helper_class<number>(*this); }
>
> friend
> ::std::ostream & operator<<(::std::ostream &os, number const &rhs)
> {
> os << rhs.value;
> return os;
> }
> };
>
> int main()
> {
> using ::std::cout;
> using ::std::endl;
>
> number x(1);
>
> cout << "Before x = " << x << endl;
> x++;
>
> cout << "After x = " << x << endl;
> x++;
> cout << "After x = " << x << endl;
>
> return 1;
> }


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk