Any word on the return-type const syntax?
Janice Caron
caron800 at googlemail.com
Sat Dec 8 01:40:14 PST 2007
On 12/8/07, Walter Bright <newshound1 at digitalmars.com> wrote:
> Janice Caron wrote:
> > Here's a typical problem.
> >
> > class MyArray(T)
> > {
> > T[] a;
> >
> > T* ptr() { return a.ptr; }
> > const(T)* ptr() const { return a.ptr; }
> > invariant(T)* ptr() invariant { return a.ptr; }
> > }
> >
> > A template helps how, exactly?
>
> TransferConst!(U,T) ptr(this U)() { return a.ptr; }
There are several things I don't understand about this example. You
seem to be suggesting that
TransferConst!(U,T)
resolves to
K(T)*
where K stands for const, invariant or nothing. That's not obvious to
me, but I'll believe you. But suppose instead I had wanted a return
type of K(T)[], or K(T)[int]? What then? Where is the return type? I
am very confused.
The next thing I don't understand is the notation
ptr(this U)()
How does that even parse? I'm not familiar with this means of
specifying template parameters. What does it mean?
The third thing I don't understand is, I see no specication of the
constancy of the member function itself. I expect to see either
const-at-the-end, or const-at-the-start, but I see neither. Where is
it?
And of course, my final question has to be, is this function still
virtual? Because if it's not, I'll just carry on writing functions the
old way. Cut and paste isn't /that/ bad.
Let's apply the readability test now. Which is more readable? First,
the current way:
T* ptr() { return a.ptr; }
const(T)* ptr() const { return a.ptr; }
invariant(T)* ptr() invariant { return a.ptr; }
Next, the way Walter suggested
TransferConst!(U,T) ptr(this U)() { return a.ptr; }
Next, my suggestion - replace "const" with some other symbol (here I
shall write "K"), and write the function exactly once.
K(T)* ptr() K { return a.ptr; }
...or, in const-at-the-front notation
K K(T)* ptr() { return a.ptr }
...or, with our proposed const(this) syntax:
K(this) K(T)* ptr() { return a.ptr }
I think my way looks most readable, but you tell me. I don't actually
care what the replacement symbol is. Obviously, "K" is an unwise
choice, but you could use any reserved word (I believe "return" was
suggested in your document), or even some combination of reserved
words like "const in" and "const out", or whatever. (And I'd also like
the symbol to be available within the body of the function).
One really important point to consider is that you need EXACTLY ONE
instantiation of the function. That is, the bytes of machine code
which comprise the function would be identical in all three cases, and
therefore need to exist only once. I suspect that your template idea,
in addition to robbing me of virtuality, would also instantiate the
function three times.
More information about the Digitalmars-d
mailing list