Function accepting variadic arguments

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 20 04:56:51 PST 2016


On 01/20/2016 04:38 AM, pineapple wrote:
> I'd like to make a constructor which takes a variable list of arguments,
> of a short list of possible types, with different handling depending on
> the type. I haven't been able to find any documentation or examples that
> did quite what I'm trying to. Help?
>
> A fun pseudocode example of what I'm trying to do:
>
> this(...){
>      foreach(argument){
>          if(argument is a number){
>              do stuff with it;
>          }else if(argument is of type A){
>              do other stuff;
>          }else if(argument is of type B){
>              yet more stuff;
>          }
>      }
> }
>

import std.stdio;

struct A {
     double d;
}

struct B {
     string s;
}

struct C {
     this(T...)(T args) {
         foreach (arg; args) {
             static if (is (typeof(arg) == int)) {
                 writefln("int: %s", arg);

             } else static if (is (typeof(arg) == A) ) {
                 writefln("A: %s", arg);

             } else static if (is (typeof(arg) == B)) {
                 writefln("B: %s", arg);
             }
         }
     }
}

void main() {
     auto c = C(42, A(1.5), B("hello"));
}

Prints:

int: 42
A: A(1.5)
B: B("hello")

And there is another example here:

 
http://ddili.org/ders/d.en/templates_more.html#ix_templates_more.tuple%20template%20parameter

Ali



More information about the Digitalmars-d-learn mailing list