const again
Walter Bright
newshound1 at digitalmars.com
Thu Dec 6 13:33:46 PST 2007
As a result of all the const comments here, and some serious semantic
problems discovered (dang it's hard to think of everything in advance),
it seems there needs to be another tweak of the const behavior.
Every time we try to sneak in "tail-const" in some form, some semantic
correctness breaks somewhere. For example, struct member functions can
be const or non-const, but there is no notion of "tail-const" for struct
member functions. Trying to accommodate this results in all kinds of
peculiar rules and inconsistencies.
The second thing that just causes endless difficulties is the idea of
using const to declare manifest constants, as in:
const x = 3;
having the same meaning as the C:
#define x 3
in that 1) x does not consume storage and 2) x is typed as int, not
const(int). For example,
auto i = x;
one would *not* want i to be typed as const(int).
So, we're going to try a new, simpler regime:
const T x;
is semantically identical to:
const(T) x;
and the type of x is const(T).
That leaves what to do about manifest constants. It occurs that we
already have a mechanism for them - enums. So why not:
enum x = 3;
enum long y = 4;
? I think that solves our problem.
There's one last problem:
class C { }
const(C)[] a;
a[3] = new C(); // error, x[3] is const
does not work with this new regime. Every twist we tried to make it work
caused other problems. Eventually, it just became clear that this just
is not going to work. But, the following does work:
a ~= new C();
a = a[1..3];
a = b;
just like for strings. One can copy, concatenate, and slice such arrays
(just like for strings). It's not so bad. Andrei also mentioned the
possibility of using a template:
TailConst!(C)[] a;
which would do whatever was necessary under the hood to allow the
elements of a to be rebound while still keeping the contents of the C
objects const.
More information about the Digitalmars-d
mailing list