about const and immutable (again)
Steven Schveighoffer
schveiguy at yahoo.com
Thu Oct 6 08:32:11 PDT 2011
On Thu, 06 Oct 2011 10:56:43 -0400, Gor Gyolchanyan
<gor.f.gyolchanyan at gmail.com> wrote:
> Hi, guys.
>
> I just made my handy parsing struct take an arbitrary range, instead
> of a dstring and immediately rain head-first into a brick wall of
> errors.
>
> There's this function:
> bool next(bool function(ElementType!InputType) pred)
>
> , where InputType is bound to be dstring and which gets called like this:
> parser.next(&isAlpha)
>
> , where isAlpha is from std.uni.
> When i do that, i get this error:
> Error: cannot implicitly convert expression (& isAlpha) of type
> bool function(dchar c) pure nothrow @safe to bool
> function(immutable(dchar))
>
> Yes, I understand why do i get this error.
> What i don't understand is: does the dchar being immutable really
> change anything?
What it does is make it so during the function, the parameter cannot be
changed. It technically has no effect on what you can pass to the
function, since as you rightly point out, ints implicitly cast between
const, immutable, and mutable.
Why did someone do it? To ensure they didn't accidentally write code that
changed the value inside the function. The compiler might also use that
information to do some optimization (i.e. avoid reloading into a
register), but I doubt it's necessary for that.
To answer your underlying question, why doesn't the delegate "just work"?
It's because D does not allow implicit casting of delegates or functions
at all. I assume this will get better at some point, because implicit
casting of delegates would make things just so much smoother in generic
programming.
-Steve
More information about the Digitalmars-d
mailing list