Eponymous template with static if

Steven Schveighoffer schveiguy at gmail.com
Wed Aug 9 18:04:19 UTC 2023


On 8/9/23 12:55 PM, Michael Galuza wrote:
> It's well known that template functions in D are just kind of eponymous 
> template:
> ```d
> T square(T)(T t) {
>      return t * t;
> }
> ```
> is lowered to
> ```d
> template square(T) {
>      T square(T t) {
>          return t * t;
>      }
> }
> ```
> 
> But if we write this:
> ```d
> template square(T) {
>      static if (true) {
>          T square(T t) {
>              return t * t;
>          }
>      }
> }
> }
> ```
> trivial expression `square(3)` won't compiled with message
> `Error: none of the overloads of template main.square are callable using 
> argument types !()(int)`.
> 
> Why? What I missed?

In order for IFTI (Implicit Function Template Instantiation) to work, 
template functions must be of a certain form. If I recall correctly, 
they must be immediate children of the template AST node. You can stuff 
other things in the template, but you can't do something like what you did.

The fact that IFTI works at all is kind of a kludge. The compiler must 
match the argument types to the function call nested in the template to 
do pattern matching, and *then* instantiate the template. In other 
words, it has to look inside before instantiation.

-Steve


More information about the Digitalmars-d mailing list