opApply and const

Steven Schveighoffer schveiguy at yahoo.com
Mon Dec 10 06:48:32 PST 2007


"Bill Baxter" wrote
>I mentioned it in another thread but I just wanted to confirm it.
> Am I right in thinking that if we want to have user types act like 
> built-in containers w.r.t iteration in D2 then we need to implement 12 
> different versions of opApply?!

Note that there is no requirement to implement the invariant versions.  An 
invariant object can be implicitly cast to a const object, and so the const 
versions can be called by invariant objects.

The only benefit of having an invariant AND a const version is to skip 
things like mutex locking in the invariant version.

I've been thinking about this for a while, and I've come to the conclusion 
that I think invariant and const functions are so damned similar, that there 
must be a way to specify them both at once.  I mean, if the only difference 
between an invariant and a const is you don't have to do mutex locks to read 
data, can't the compiler just make 2 versions of a const function, and not 
do the synchronized(X) where X is invariant?  It'd be like an automatic 
template, where any time you specify a const parameter (including 'this'), 
it could also generate a function where the const parameter is invariant.

I know Walter wants to promote invariant functions as a way to help avoid 
thread mistakes, but I highly doubt I will be a common practice, especially 
by people who are not familiar with the perils of threading.  This seems to 
me to be similar to inline, where the compiler would know better than me 
when it could optimize by calling an invariant version.

-Steve 





More information about the Digitalmars-d mailing list