Making RCSlice and DIP74 work with const and immutable

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Sat Feb 28 22:39:34 PST 2015


On Sun, Mar 01, 2015 at 12:53:24PM +1000, Manu via Digitalmars-d wrote:
> On 1 March 2015 at 12:48, Andrei Alexandrescu via Digitalmars-d
> <digitalmars-d at puremagic.com> wrote:
> > On 2/28/15 6:33 PM, Manu via Digitalmars-d wrote:
> >>
> >> one of the biggest recurring
> >> complaints relating to the D type system
> >
> >
> > That didn't get talked about in I don't remember. -- Andrei
> 
> So, what's the solution?
> I've never complained about it, but I still have this problem
> regularly. The solution in my experience is; 'everything is always
> mutable'.

I ran into the same problem, and as a result I hardly ever make use of
D's const system.

One possible solution that occurred to me, though, is to introduce a
kind of "logical const" template that constructs a partially-const type,
with the "logical data" parts const/immutable/etc., but the "metadata"
parts mutable. User-defined attributes could be used for this purpose:

	struct Metadata {}

	class MyClass {
		int field; // regular data field
		@Metadata int fieldCache; // metadata
		...
	}

	template Const(T) {
		class Const {
			const {
				// insert stuff not marked with
				// @Metadata here
			}
			// insert stuff marked with @Metadata here
		}
	}

So then Const!MyClass is a modified version of MyClass where the data
fields are const (similarly, we can define Immutable for the analogous
purpose) but the fields marked as metadata will remain mutable.

Of course, this is just a crude first stab at the problem; I'm sure
there's plenty of room for refinement to make it more usable, and to
address some obvious roadblocks, like how to make MyClass implicitly
convertible to Const!MyClass, etc.. But it seems likely that D's
template machinery can actually express this in a way that does not
violate the guarantee of physical const.


T

-- 
Doubt is a self-fulfilling prophecy.


More information about the Digitalmars-d mailing list