Char literals
Steven Schveighoffer
schveiguy at yahoo.com
Fri Nov 6 05:09:32 PST 2009
On Fri, 06 Nov 2009 06:24:51 -0500, Eldar Insafutdinov
<e.insafutdinov at gmail.com> wrote:
> I've just written a simple replicate function (the one from std.range
> does not work in CTFE):
> T[] replicate(T)(int n, T value)
> {
> T[] ret;
> if (n > 0)
> {
> for(int i = 0; i < n; i++)
> ret ~= value;
> }
> return ret;
> }
> it's not the best implementation, but that's not the thing I want to say
> today. When I call it
>
> string str = replicate(5, 'a');
>
> I get
>
> moc.d(370): Error: cannot implicitly convert expression
> (replicate(5,',')) of type char[] to string
>
> That means that char literals are "char", but not "immutable(char)". I
> remember the whole conversation about array literals, but char literals
> are closer to those of the string. What's the reasoning behind leaving
> them as mutable char?
a value type such as char makes no sense as an immutable entity. First of
all, an immutable char can be implicitly cast to and from a mutable char.
Although it might seem incorrect, since it is a value type, assigning it
to an immutable variable makes a copy anyways, so the
mutability/immutability of the original variable stays intact.
You bring up a legitimate concern. However, you are probably never going
to see 'a' by itself typed as an immutable char, because mutable makes the
most sense as the default constancy of a value type literal. It seems
that string literals being typed as immutable(char)[] is an inconsistency
in the world of D literals that always needs to be handled specially.
What you probably want to have is a specialization for your template.
Again, another use case for unique(T)...
BTW, you can save a loop by doing this:
T[] ret = new T[n];
ret[] = value; // assign value to all elements of ret
-Steve
More information about the Digitalmars-d
mailing list