IFTI with D2?

Steven Schveighoffer schveiguy at yahoo.com
Wed Nov 7 08:11:29 PST 2007


"Frank Benoit" wrote
> The const thing makes IFTI hard.
>
> uint searchPattern(T)( T[] arg1, T[] arg2 ){ ... }
>
> The function shall accept mutable/const/invariant data for both arguments.
>
> searchPattern( "abc".idup, "a".idup ); // (1) compiles
> searchPattern( "abc".dup,  "a".dup  ); // (2) compiles
> searchPattern( "abc".idup, "a".dup  ); // (3) doesn't compile
>
> (1) and (2) will result in independant version of the function?
>
> Is there a solution/workaround?
> Is this a compiler bug?

I have some more thoughts on this.

I think part of the problem is that casting X to const X might be 
interpreted the same as casting X to some other type Y which is implicitly 
cast-able (i.e. casting char[] to const(char)[] is the same as casting int 
to long).  Since any type can be cast to a const version of that type, and 
the cast does NOT alter the data type in terms of storage, I think there 
should be some special rules regarding const for IFTI.  For instance, if you 
have an argument to a template function that is a const argument, like so:

f(T)(const(T)[] arg1)

Then calling f with a mutable T, a const T or an invariant T should result 
in the SAME template instantiation.  I think this is doable, but only for 
const.  Basically, this is done by the compiler recognizing that the 
template argument is going to be const, so the compiler should cast the 
argument to const before attempting to instantiate the template.  In code 
this reads:

f(x);
is equivalent to:
f(cast(const)x);

This won't fix your example, but in essence, your second line wouldn't 
compile unless it's arguments were const anyways, so the example really 
should be:

uint searchPattern(T)( const(T)[] arg1, const(T)[] arg2 ){ ... }

Regarding your concern about specifying that an argument must be mutable, 
well, that should work itself out.  When the compiler attempts to 
instantiate a template version with a non-mutable type, it will fail to 
compile at the point where you change it.  So I don't think you need a 
special interpretation by the compiler.

So I think this one fix will solve the problem.  I will add this enhancement 
to the D bug system, and we'll see what happens.

-Steve 





More information about the Digitalmars-d mailing list