const debacle
Janice Caron
caron800 at googlemail.com
Sat Mar 22 09:26:25 PDT 2008
On 22/03/2008, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
> T[] f(T)(T[] buf)
>
> And it accomplishes what you are trying to do (instantiates a version based
> on the constness of T).
There is a difference. Your template has an infinite number of
possibilities for T, whereas my suggestion has exactly three
possibilities for K.
> This does not solve the problem that I had originally queried about. The
> problem with your method is still that the non-const version does not
> guarantee that f does not change the input buffer.
I think it does actually, because if the template compiles for K ==
const, then the code does not modify the buffer - and /the same code/
is generated in all three cases, remember.
(OK, there could be exceptions to that rule if you've got some static
iffiness going on, but I think that's rare enough that it shouldn't
stomp on the idea).
But if you /really/ want to be sure, you only have to write your
function slightly differently, as below.
> I want to specify that
> the function does not change the input buffer, and returns the same type as
> passed in (without duping the input).
I think you can still solve your particular problem with my scheme by doing
K(char)[] f(const K)(K(char)[] buf_)
{
K(char)[] ret;
const(char)[] buf = buf_;
// never refer to buf_ again.
return ret;
}
If you don't like the notion of having to remember not to refer to
buf_ again within the function, more exotic possibilities remain, such
as:
K(char)[] f(const K)(K(char)[] buf)
{
K(char)[] f_(const(char)[] buf)
{
/*...*/
}
return f_(buf);
}
So it /can/ be done.
More information about the Digitalmars-d
mailing list