const challenge

Sergey Gromov snake.scaly at gmail.com
Fri Feb 1 10:45:50 PST 2008


Kris Wrote:
> "Steven Schveighoffer" <schveiguy at yahoo.com> wrote ...
> >> As far as the example api-style goes, here's hoping that this will work 
> >> correctly in D2:
> >>
> >> # char[] other (in char[] input, char[] output = null);
> >>
> >> where 'in' indicates only that the input will not be modified by the 
> >> callee. By doing so, the following should be clean:
> >>
> >> # char[] nested (in char[] input, char[] output = null);
> >> #
> >> # auto result = nested (other (x, y));
> >>
> >> Given that the input cannot be modified, you should also be able to pass 
> >> a const or invariant string as an 'in' parameter; right?
> >>
> >> # auto result = other ("foo");
> >
> > 'in' isn't necessary in my mind.  How can the callee modify the string if 
> > the callee is in the same thread?

Um... by modifying it ?  If it's not either 'in' or 'const' ?

> > I think what you want here is 
> > const(char)[] input.  This specifies that the input is not supposed to 
> > change.
> 
> 
> only because 'in' actually appears to do what it implies, whilst apparently 
> accepting mutable, const, or invariant. Not to mention it is a darn sight 
> more readable than the decorative alternatives.
> 
> BTW: how would one pass an invariant string as a const(char[]) argument, per 
> the above example? Isn't there a cast required?

Anything casts to 'const' implicitly because 'const' doesn't violate any
contracts for other types.  The 'in' in D2 seems to be just an alias
for 'const'.

> >> If that's the case, then ok.
> >>
> >> Assuming all is kosher so far, sliced 'in' arguments should also be 
> >> accepted in the same fashion:
> >>
> >> # auto result = other ("foo"[0..2]);
> >>
> >
> > if you replace in with const, then yes.
> 
> Are you quite certain of that?

'const' and 'in' work exactly the same, just checked.

void foo(in char[] s) { writeln(s); }
void bar(const char[] s) { writeln(s); }

foo("test");
foo("test"[0..2]);
foo("test".dup);
bar("test");
bar("test"[0..2]);
bar("test".dup);

compiles and works correctly.

SnakE



More information about the Digitalmars-d mailing list