www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - struct opEquals

reply SiegeLord <none none.com> writes:
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);
}

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)?

-SiegeLord
Mar 09 2011
parent reply "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Wed, 09 Mar 2011 11:40:25 -0500, SiegeLord <none 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
Mar 09 2011
parent reply SiegeLord <none none.com> writes:
Steven Schveighoffer Wrote:

 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
It worked fine in D1. Or did you mean that the mis-designed feature is the const system? Anyway, thanks for the link to the bug report. I'll work around it for now. -SiegeLord
 
 -Steve
Mar 09 2011
parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Wed, 09 Mar 2011 12:15:26 -0500, SiegeLord <none none.com> wrote:

 Steven Schveighoffer Wrote:

 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
It worked fine in D1. Or did you mean that the mis-designed feature is the const system?
No, the mis-designed feature is the compiler requiring that specific signature in D2. Const is not the mis-designed feature. It works in D1 because D1 doesn't generate intelligent opEquals for structs that do not have them, it just does a bit compare. For example, if you did this in D1, it fails the assert: struct S { string name; } void main() { S s1, s2; s1.name = "hello".dup; s2.name = "hello".dup; assert(s1 == s2); // fails in D1, should pass on D2. } -Steve
Mar 09 2011