Templates problem

Lodovico Giaretta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 7 05:28:21 PDT 2016


On Wednesday, 7 September 2016 at 11:37:44 UTC, Russel Winder 
wrote:
> I'd prefer immutable, but const sometimes has to do. The idea 
> is to find out how to enforce single assignment in D.

Everything depends on what you mean by "single assignment".

If you mean "I can't use opAssign", then const is definitely too 
strong. In this case, you can write a simple type wrapper that 
disables opAssign, while providing all other functionalities.

If you mean "Methods do not mutate objects; instead, they return 
new objects, mutated", the issue is deeper. In fact, input ranges 
and output ranges cannot (by definition) fulfill this 
requirement. Other ranges (forward, bidirectional, random) can 
fulfill this requirement, but it's very expensive, as it requires 
a new copy of every range every time you want to popFront or 
popBack. The same goes for every other type with mutable methods. 
If you really want this behaviour, you can easily write (again) a 
type wrapper that forwards every const method call while 
intercepting every mutable method call and applying it to a new 
copy that is returned. But I think it will severely hurt 
performance and readability.


More information about the Digitalmars-d-learn mailing list