Problem with implicit template instantiation

Steven Schveighoffer schveiguy at yahoo.com
Sun Jul 6 20:49:41 PDT 2008


"Bill Baxter" <dnewsgroup at billbaxter.com> wrote in message 
news:g4s05a$2l0l$1 at digitalmars.com...
> Clemens Hofreither wrote:
>> Hi all.
>>
>> I'm currently playing around with template metaprogramming in D. I've 
>> encountered a problem with implicit instantiation of templates that I 
>> don't really understand, and I thought somebody here could shed some 
>> light on it. Consider the following code:
>>
>> template MyType(T)
>> {
>> alias T MyType;
>> }
>>
>> void mytest(T)(MyType!(T) x)
>> {
>> }
>>
>> void main()
>> {
>> MyType!(int) x;
>> mytest(x);
>> }
>>
>> This does not work. I would expect the template mechanism to recognize 
>> that the argument to mytest is an instance of MyType!(int) and hence 
>> instantiate T with int, but instead I get the errors
>> template mytest(T) does not match any template declaration
>> template mytest(T) cannot deduce template function from argument types 
>> (int)
>>
>> I've also tried replacing alias by typedef, with the same results. 
>> Instantiating the template explicitly seems to work, but I would first 
>> like to know *why* I can't do it like this before I use any workarounds. 
>> Any pointers? Thanks in advance.
>>
>> Oh, and this is DMD v1.029.
>
> It's just not that smart.  It's a specialization so you have to use 
> specialization syntax.  Something like:
>
> void mytest(T : MyType!(S), S) {}
>
> But note that using specialization also disables IFTI.
> In D2 you should be able to use a constraint to do something like
>
> void mytest(T) if(is(T : MyType!(S))) {}
>
> My syntax is probably all wrong here, but that's the idea anyway.
>
>
> Here's a bug marked fixed with a similar goal to yours:
>     http://d.puremagic.com/issues/show_bug.cgi?id=1661
> The discussion may be useful.

I have an open enhancement request on this:

http://d.puremagic.com/issues/show_bug.cgi?id=1653

I think the main issue is really that there is no 'reverse' path from the 
alias to the parameter to a specific template.  That is given the type 
MyType!(T), which is really an alias for T, What template should the 
compiler use to deduce the argument?  What if there were multiple templates 
that aliased to T, should those also be assumed to be MyType!(T)?  What if 
you pass in just a T?  Technically it's the same thing.

I think these are the issues that makes it tough to do the IFTI.  I think we 
are spoiled because things like:

void f(T)(T[] x)

but that's a much simpler case to solve.

-Steve 




More information about the Digitalmars-d-learn mailing list