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

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Mon Jun 30 18:13:10 PDT 2014


On Monday, June 30, 2014 22:22:50 francesco cattoglio via Digitalmars-d wrote:
> I found out today that the following code won't compile:
>
> import std.conv;
>
> class MyClass {}
>
> void doStuffKo(const MyClass instance)
> {
>   string temp = to!(string)(instance);
> }
>
> Everything compiles fine if I remove the const from the function
> signature.
> I found out this issue named in earlier threads but I could not
> find any bug about it on the issue tracker. Is this a bug, a
> missing feature, or is this something that is almost impossible
> to achieve and therefore not implemented on purpose?

It's a consequence of Object's toString not being const, but making it const
would cause other problems. As it is, comparing const Objects only works
because of a hack (the runtime actually casts aways const to do the
comparison, which risks serious bugs if opEquals actually mutates something -
e.g. for caching).

The long term plan is to remove toString, opEquals, toHash, and opCmp from
Object so that the derived classes can decide whether to make them const or
not. Unlike Java and C#, we have proper templates, so we can templatize all of
the stuff in the runtime which uses those functions so that they don't have to
be on Object.

https://issues.dlang.org/show_bug.cgi?id=9769
https://issues.dlang.org/show_bug.cgi?id=9770
https://issues.dlang.org/show_bug.cgi?id=9771
https://issues.dlang.org/show_bug.cgi?id=9772

Unfortunately, there hasn't been a lot of progress on what needs to be done to
remove those functions from Object thanks in part to some compiler bugs as
well as how thorny the AA implementation is. We intend to get there eventually
though, which would solve your problem (assuming that you're derived class
declared an appropriate toString of course).

- Jonathan M Davis



More information about the Digitalmars-d mailing list