Am Fri, 26 Jan 2018 19:45:54 +0000 schrieb timotheecour <timothee.co...@gmail.com>:
> this compiles, but equivalent in C++ (const int vs int) would > give a > compile error (error: redefinition of 'fun'); what's the > rationale for > allowing these overloads? > > ``` > void fun(int src){ writeln2(); } > void fun(immutable int src){ writeln2(); } > void fun(const int src){ writeln2(); } There is also `inout` and `shared`. Granted, for basic types it makes no difference, but once references are involved you benefit from keeping the qualifier. A const or mutable string must be assumed to change after the function returns. Immutable strings on the other hand can be copied by reference. Immutable stuff is also implicitly shared, so can be used by multiple threads without synchronization. Optimizations for mutable versions only are also possible, like in-place editing. If your implementation is the same for immutable and mutable qualifiers, just provide the const version, but keep in mind that the type qualifiers are lost then. Any functions you call further down will also use their "const" implementation. Doing this as an overload of course helps with generic programming and maintenance. You can migrate from "const" only to providing multiple implementations without inventing new names or breaking code. It may also have to do with how C++'s const is not much more than a static check, while D's immutable is both transitive and supposed to give strong guarantees that the object never changes. That assumption is somewhat tied to the idea that immutable objects are either in read-only sections of the executable or that the garbage collector will keep them alive until all references are gone. -- Marco