opMul

Simen Kjaeraas simen.kjaras at gmail.com
Mon Mar 3 06:03:48 PST 2008


On Mon, 03 Mar 2008 02:01:09 +0100, Bill Baxter  
<dnewsgroup at billbaxter.com> wrote:

> 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;
>>     }
>> }
>
> I can't keep up here.  Is a trailing 'const' legal D syntax now?
>
> --bb

Well, in a way. After becoming sober, I re-read this today and... ouch.

It seems to me that the trailing const says "this function is const,  
really!" while in fact, it is not. Case in point: above code, which  
obviously changes this.bar.

Walter (or anyone else who understands const), is this how things are  
supposed to be?

correct code would be as follows:

import std.stdio;

struct Foo1
{
	int bar;
	
	Foo1 opMul(int rhs)
	{
		Foo1 tmp;
		tmp.bar = bar * rhs;
		return tmp;
	}
}

struct Foo2
{
	int bar;
	
	const Foo2 opMul(int rhs) // difference here
	{
		Foo2 tmp;
		tmp.bar = bar * rhs;
		return tmp;
	}
}

void main()
{
	const Foo1 foo1 = Foo1(4);
	Foo1 bar1 = foo1 * 3;	// fails

	const Foo2 foo2 = Foo2(4);
	Foo2 bar2 = foo2 * 3;	// works
}


This correctly fails if this.bar is changed.



More information about the Digitalmars-d mailing list