Nobody understands templates?

Nick Sabalausky SeeWebsiteToContactMe at semitwist.com
Tue Mar 4 18:27:54 PST 2014


On 3/3/2014 5:35 PM, Chris wrote:
>
> Maybe I'm a bit too philosophical about this. But consider the following
> (made up) case:
>
> struct MyTemp(T) {
>      // ...
>      T add(T a, T b) {
>          if (a is string && b is string) {
>                return a~b;  // or return a~"+"~b; or whatever
>          } else if (a is integer && a is integer) {
>                return a+b;
>          }
>      }
> }
>
> I don't know if this can be considered a "pure" template. It is a
> template of sorts, but the type specialization in the function add makes
> it a watered-down template,

Any useful template function already works that way. The mere + operator 
is *not* one single operation, but a whole category of opcodes which are 
chosen based on the operand's type. Thus, + can be thought of as a 
built-in template that [roughly] does this:

T opPlus(T a, T b) {
     if (T is integer) {
         [asm opcode for 32-bit addition] a, b
     } else if (T is ubyte) {
         [asm opcode for 8-bit addition] a, b
     } else if (T is float) {
         [asm opcode for floating point addition] a, b
     }
}

Specialization is what makes function templates useful. Some of the 
specialization is explicit (static if) and some is implicit (+ 
operator). But without specialization (explicit or implicit), all 
instantiations would be identical. If all instantiations are identical, 
why even have a template in the first place?



More information about the Digitalmars-d-learn mailing list