[comp.lang.c++] questions about overloaded operators

mikpe@majestix.ida.liu.se (Mikael Pettersson) (09/21/89)

(my statements here are made relative to C++ as implemented by cfront 1.2.1)

1) Why does C++ *require* that at least one of the operands to an
overloaded operator *must* be a class object? Does Ver. 2.0 still
enforce this restriction?

2) According to the reference manual, conversion constructors
( class X { ... X(type); }; ) are supposed to be used for conversion
of function arguments. But apparently they are *not* used to rewrite
arguments to operators (implying that operators aren't really "just"
functions operator@(...) ), making the follwing attempt fail:
	class Pair { ... };
	class Sym {
		...
		Sym(char*);
		Pair operator/(int);	// yes, I know it looks suspect
	};
	class Env {
		...
		Env operator[](Pair);	// update
	};
	foo() {
		Env e;	// empty env
		e = e["foo"/5];		// here, I'd like Sym::Sym(char*) to
					// be applied to "foo" automatically.
		...			// (since Pair operator/(char*,int)
					// is outlawed)
	}
(if you haven't guessed it, I'm trying to write environment updates in
the usual mathematical style e[name/val] rather than e.update(name,val) )

Again, does Ver 2.0 do what I want?


	/Mike
-- 
Mikael Pettersson, Dept of Comp & Info Sci, University of Linkoping, Sweden
email: mpe@ida.liu.se  or  ..!{mcvax,munnari,uunet}!enea!liuida!mpe

jima@hplsla.HP.COM (Jim Adcock) (09/27/89)

// Sorry, I don't believe you can do what you want to do.  You're asking
// that the meaning of an expression be determined by context, and C++ [2.0]
// won't do that [thank gawd.]  C++ will determine the meaning of an expression
// regardless of its context, then coerce the resultant type to what you have
// specified.  Below find what I believe are your reasonable legal options
// in C++:

// (from your example:)

class Pair {};

class Sym {
public:
	Sym(char*);
	Pair operator/(int);	
};

class Env {
public:
	Env operator[](Pair);
};

void foofoo() {
	Env e;	

// option one:
	Sym foo("foo");
	e = e[foo/5];

// option two:
	e = e[Sym("foo")/5];

// option two_b:
	e = e[(Sym)"foo"/5];
}

// Personally, option one -- requiring you to declare your symbol before using
// it -- seems pretty reasonable to me.