Re: [boost] Postfix Increment Operator
by Richard Peters other posts by this author
Jun 11 2002 8:10AM messages near this date
Re: [boost] Postfix Increment Operator
|
Re: [boost] Postfix Increment Operator
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@[...].com>
> 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;
> }
_______________________________________________
Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Thread:
Powell, Gary
=?iso-8859-1?Q?Terje_Sletteb=F8?=
Daniel Frey
Daniel Frey
David Abrahams
Richard Peters
David Abrahams
Lars Gullik =?iso-8859-1?q?Bj=F8nnes?=
Brad King
Brad King
|