Bug or Feature? compile error: to!string(const Object)

via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 2 06:30:54 PDT 2014


On Wednesday, 2 July 2014 at 11:33:56 UTC, Wanderer wrote:
> On Wednesday, 2 July 2014 at 09:24:39 UTC, Jonathan M Davis via 
> Digitalmars-d wrote:
> "Languages like Java and C# are forced to, because they do not 
> have proper templates and thus have to use Object directly in 
> many cases."
>
> That's not exactly true. The main reason why Object class has 
> these methods, is the ability to define general contracts for 
> these methods. For example, Object defines once and for all 
> that toString() returns String representing object's contents, 
> or that equals() and hashCode() results comply with each other. 
> If you remove these methods from Object, you will dispense 
> these contracts as well, forcing programmers to implement these 
> methods in least predictable way. That will cause chaos.

No, it won't. The standard way to convert an object to a string 
is calling `std.conv.to`. This is a templated function that's 
capable of inspecting the type it's passed. If the type has a 
`toString` method (as is currently the case for Object and 
descendants), it will be used. If not (e.g. for structs that 
don't define `toString`), it has a default implementation that 
lists the fields:

     struct StructWithToString {
         int x, y;

         string toString() const {
             return "I'm a struct.";
         }
    }

     struct StructWithoutToString {
         int x, y;
     }

     void main() {
         import std.stdio;
         import std.conv : to;

         StructWithToString s1;
         StructWithoutToString s2;
         writeln(s1);
         writeln(s2);
     }

Outputs:

     I'm a struct.
     StructWithoutToString(0, 0)

This default formatting can easily be extended to objects (if it 
doesn't work already). And for opEquals/toHash, there can be a 
default implementation too, if this is considered useful (I 
believe it is already provided for structs).


More information about the Digitalmars-d mailing list