TITLE: Example usage of comma operator 


PROBLEM: jrobie@netmbx.netmbx.de (Jonathan Robie)

Can anybody give me examples where overloading , or ->* is useful?
Nothing occurs to me offhand...


RESPONSE: grumpy@cbnewse.cb.att.com (Paul J Lucas)

	Never though of a use for ->*, but "," is useful for building
	lists ro supplying a varying number of *type-safe* arguments (as
	opposed to using varargs.h:

		BitVector b;

		b += 1,5,8;	// turn on bits 1, 5, and 8
	
	You can't use mutiple +='s because the associativity is wrong.


RESPONSE: jrobie@netmbx.netmbx.de (Jonathan Robie)

Thanks for the example.  As you point out, a chain of += does not work
because the associativity is wrong.  If I try this:

	b += 1 += 5 += 8;

then the 5 += 8 operation will be performed first since assignment
operators associate from right to left.  The comma operator implementation
is elegant.  However, I am not sure that I understand how you implemented
this.  I have tried implementing it, and my implementation is limited
and a little bit dangerous.  Here it is:

#include <iostream.h>

class BitVector
{
	unsigned long bits;

public:
	BitVector() { bits = 0; }
	BitVector& operator += ( int i) { bits |= 1 << i; return *this;}
	BitVector& operator , ( int i ) { this->operator+=(i); return *this;}
	Print() { cout << bits << endl; }
};

main()
{
BitVector bv;

	bv += 1;
	bv.Print();

// += has a higher precedence than , and is executed first.

	bv += 0,2,3;
	bv.Print();
			
	return 0;
}

This is fine as long as you are only implementing +=, but what if
we also want to implement -= to clear our bits:

	bv -= 1,2,3;

If the statement

	bv += 1,2,3;

sets bits 1,2,3, many people might expect our -= statement to clear
the same bits.  Since the comma operator has a lower precedence than
the assignment operator it will not do this.  First bit 1 is cleared,
then bv.operator,(2) is called, then bv.operator,(3) is called.  But
our operator,() function *sets* the bit, so our -= statement clears
bit 1 and sets bits 2 and 3.

It is not reasonable for me to want the -= statement to clear all
three bits since this would violate C++ precedence.  You might say
that the real problem is that I am still not comfortable with the
precedence that the , operator has in C and C++.  Actually, the
operator behaves just as it is defined in the language.
