Template overloading
Downs
default_357-line at yahoo.de
Mon Sep 17 03:28:14 PDT 2007
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
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
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iD8DBQFG7la9pEPJRr05fBERAhuxAKCX1WF6s3UxK3c1tznI5WG2Wg+IswCdGyBl
UAkz2n9mGqR1sMRpVpV4xZI=
=8UpJ
-----END PGP SIGNATURE-----
More information about the Digitalmars-d-learn
mailing list