opMul

Denton Cockburn diboss at hotmail.com
Sun Mar 2 19:10:36 PST 2008


On Mon, 03 Mar 2008 01:47:33 +0100, Simen Kjaeraas wrote:

> On Sun, 02 Mar 2008 20:10:23 +0100, Denton Cockburn <diboss at hotmail.com>  
> wrote:
> 
>> Is there a reason why opMul cannot be called on a constant object?
>>
>> This restriction is hardcoded (I clearly don't have a choice for my  
>> object).
> 
> 
> That would be due to opMul not being defined as a const function.
> 
> 
> import std.stdio;
> 
> struct Foo1
> {
> 	int bar;
> 	
> 	Foo1 opMul(int rhs)
> 	{
> 		bar *= rhs;
> 		return *this;
> 	}
> }
> 
> struct Foo2
> {
> 	int bar;
> 	
> 	Foo2 opMul(int rhs) const // difference here
> 	{
> 		bar *= rhs;
> 		return *this;
> 	}
> }
> 
> void main()
> {
> 	const Foo1 foo1 = Foo1(4);
> 	Foo1 bar1 = foo1 * 3;	// fails
> 
> 	const Foo2 foo2 = Foo2(4);
> 	Foo2 bar2 = foo2 * 3;	// works
> }

A function does not have to be constant to allow a constant parameter.
It just has to promise not to change the parameter.

I don't understand why opMul would change the parameter, or more
importantly, why it can't be stated that it WONT change the parameter in
any cases.

I think this is related to what Janice spoke about.  The constant changes
that have taken place need to be properly incorporated into the language
and library.  There are a lot of places where constant doesn't work as
would be intuitively expected.



More information about the Digitalmars-d mailing list