Thread overview
Template overloading
Sep 17, 2007
Oliver
Sep 17, 2007
Downs
Sep 17, 2007
Regan Heath
September 17, 2007
Hi everyone,

i would like to overload template functions. The following code shows what i'd like.

import std.stdio;

void test(T1)(T1 n1) {
    writefln("number: ", n1); }

void test(T2)(T2[] array ) {
    writefln("array: ", array); }


void main () {
    double d1 = 2.1;
    double d2 = 1.2;
    double[] da1 = [d1, d2];

    test(d1);
    test(da1);
}

This fails (to my understanding) because the templates are not specialized enough. Is it possible to specialize the template to either accept an array of numbers (of any type) or a single number (of any type).

Any comments are appreciated. Thanks
September 17, 2007
Oliver wrote:
> Hi everyone,
> 
> i would like to overload template functions. The following code shows what i'd like.
> 
> import std.stdio;
> 
> void test(T1)(T1 n1) {
>     writefln("number: ", n1); }
> 
> void test(T2)(T2[] array ) {
>     writefln("array: ", array); }
> 
> 
> void main () {
>     double d1 = 2.1;
>     double d2 = 1.2;
>     double[] da1 = [d1, d2];
> 
>     test(d1);
>     test(da1);
> }
> 
> This fails (to my understanding) because the templates are not specialized enough. Is it possible to specialize the template to either accept an array of numbers (of any type) or a single number (of any type).
> 
> Any comments are appreciated. Thanks

The only way I can see to do this is with static if
e.g.

import std.stdio;

template isArray(T) { const bool isArray=false; }
template isArray(T: T[]) { const bool isArray=true; }

void test(T)(T n) {
  static if(isArray!(T)) writefln("array: ", n);
  else writefln("number: ", n);
}

 --downs
September 17, 2007
Oliver wrote:
> Hi everyone,
> 
> i would like to overload template functions. The following code shows what i'd like. 
> 
> import std.stdio;
> 
> void test(T1)(T1 n1) {
>     writefln("number: ", n1); }
> 
> void test(T2)(T2[] array ) {
>     writefln("array: ", array); }
> 
> 
> void main () {
>     double d1 = 2.1;
>     double d2 = 1.2;
>     double[] da1 = [d1, d2];
> 
>     test(d1);
>     test(da1);
> }
> 
> This fails (to my understanding) because the templates are not
> specialized enough. Is it possible to specialize the template to
> either accept an array of numbers (of any type) or a single number
> (of any type).
> 
> Any comments are appreciated. Thanks

My first instinct is to try this:

void test(T2 : T2[])(T2[] array ) {
    writefln("array: ", array); }

but, just like every other time I have tried to use template specialization I find that I cannot also use argument deduction:

template <file>.test(T : T[]) specialization not allowed for deduced parameter T

Granted the work around is simply to not use argument deduction but it's a real PITA.

Regan