struct opEquals

Steven Schveighoffer schveiguy at yahoo.com
Wed Mar 9 09:06:58 PST 2011


On Wed, 09 Mar 2011 11:40:25 -0500, SiegeLord <none at none.com> wrote:

> 1) Why does this code not work (dmd 2.051) and how do I fix it:
>
> struct S
> {
> 	static S New()
> 	{
> 		S s;
> 		return s;
> 	}
> 	
> 	const bool opEquals(ref const(S) s)
> 	{
> 		return true;
> 	}
> }
>
> void main()
> {
> 	S s;
> 	assert(s == S.New);
> }

Because passing an argument via ref means it must be an lvalue.  New()  
returns an rvalue.

However, that restriction is lifted for the 'this' parameter, so the  
following should actually work:

assert(S.New() == s);

>
> 2) Why is the type of struct opEquals have to be const bool opEquals(ref  
> const(T) s)? Why is it even enforced to be anything in particular (it's  
> not like there's an Object or something to inherit from)?

It's a mis-designed feature of structs.  There is a bug report on it:

http://d.puremagic.com/issues/show_bug.cgi?id=3659

-Steve


More information about the Digitalmars-d-learn mailing list