const

Steven Schveighoffer schveiguy at yahoo.com
Mon Mar 31 08:45:09 PDT 2008


"Walter Bright" wrote
> I understand what you're saying. It's simply finding a method of 
> transferring the 'constness' of the function argument to the function 
> return type, without changing the contents of the function.
>
> Note that this is *not* a problem with const or invariant, it's a 
> notational problem.
>
> This is currently done in C++ (and D) by writing each function twice. 
> Obviously, that is hardly ideal.
>
> There have been some proposals to deal with it, but the current front 
> runner is one Andrei came up with:
>
> typeof(a) foo(const(T) a) { ... }

What if the return can come from multiple inputs?  Such as the min/max 
function:

typeof(a or b?) min(const(T) a, const(T) b) {...}

Note that if 'min' is called with a being mutable and b being invariant, the 
result must be const.

What about declaring intermediate variables:

typeof(a) foo(const(T) a)
{
    ???(T) b = a;
}

How is this enforced?

typeof(a) foo(const(T) a, const(T) b)
{
   return b;
}

void f()
{
   T a;
   invariant(T) b;
   a = foo(a, b); /// removes invariance of b, should be an error
}

I think in order to implement this properly, you need a new constancy 
modifier as we have discussed in 'const debacle' and 'proposal for scoped 
const contracts'  Otherwise, you are relying on templates which would not 
always enforce the const contract, and which generate 3 identical functions.

-Steve 





More information about the Digitalmars-d mailing list