digitalmars.D.learn - struct opEquals
- SiegeLord (21/21) Mar 09 2011 1) Why does this code not work (dmd 2.051) and how do I fix it:
- Steven Schveighoffer (9/31) Mar 09 2011 Because passing an argument via ref means it must be an lvalue. New()
- SiegeLord (4/9) Mar 09 2011 It worked fine in D1. Or did you mean that the mis-designed feature is t...
- Steven Schveighoffer (18/24) Mar 09 2011 No, the mis-designed feature is the compiler requiring that specific
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
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
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=3659It 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
On Wed, 09 Mar 2011 12:15:26 -0500, SiegeLord <none none.com> wrote:Steven Schveighoffer Wrote: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. } -SteveIt's a mis-designed feature of structs. There is a bug report on it: http://d.puremagic.com/issues/show_bug.cgi?id=3659It worked fine in D1. Or did you mean that the mis-designed feature is the const system?
Mar 09 2011