Q about template function overloads

Lutger lutger.blijdestijn at gmail.com
Mon Dec 18 05:22:45 PST 2006


Bill Baxter wrote:
> Given a templated array-like class that looks like:
> 
> class Array(T)
> { ... }
> 
> 
> How can I write a two overloaded versions of func, one which takes T[] 
> and one which takes Array!(T), and have both return an Array!(T)?
> 
> In this case the Dummy trick[1] doesn't seem to be of much use.
> [1] http://d.puremagic.com/issues/show_bug.cgi?id=337
> That only seems to work when the Dummy is a specific type, not a 
> parameterized type.
> 
> Am I stuck with static if's in this case?
> 
> What I'd like to write:
> 
> ---------
> // clean simple obvious, but doesn't compile
> Array!(T) func(T)(Array!(T) a)
> {
>     ...
> }
> 
> Array!(T) func(T)(T[] a)
> {
>     ...
> }
> ---------

Hopefully these bugs you mention get fixed. I'm not very big on 
templates, something like this is how I would do a workaround:

class Array(T)
{
     alias T* ptr; // tag that matches T[].ptr
     ...
}

Array!(T) func(A, T = typeof(*A.ptr) )(A array)
{
     static if ( is(A == Array!(T)) )
     {
         pragma(msg, "Array!(T)");
         ...
     }
     else
     {
         pragma(msg, "T[]");
         ...
     }
}

Don't know if it is acceptable to you, but it works.



More information about the Digitalmars-d-learn mailing list