Variadic template parameters T... bounding

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 2 05:52:55 PST 2016


On Tuesday, 2 February 2016 at 13:20:33 UTC, Voitech wrote:
> Hi, Is it possible to bound T... in template with some type ? 
> For single Parameter declaration it can be done by T:SomeType 
> but variadics does not seems to have that possibility ?
> Cheers

Two possible solutions... If you don't need to know the number of 
arguments at compile time, you can use normal variadic arguments:

     void test(T)(T[] args...) {
         import std.stdio;
         writeln(T.stringof);
     }

     class A     { }
     class B : A { }
     class C : A { }

     void main()
     {
         test(1,2,3);    // int
         test(4,5,6.9);  // double
         static assert(!__traits(compiles, test(1,"xyz",9)));
         // unfortunately, this doesn't work either:
         //test(new B(), new C());
     }

The last call should work IMO, but it doesn't. I believe that's a 
compiler bug.

The other solution is to use `CommonType` as a template 
constraint:

     import std.traits;

     void test(T...)(T args)
     if(!is(CommonType!T == void))
     {
         import std.stdio;
         writeln(T.stringof);
     }

     class A     { }
     class B : A { }
     class C : A { }

     void main()
     {
         test(1,2,3);            // (int, int, int)
         test(4,5,6.9);          // (int, int, double)
         static assert(!__traits(compiles, test(1,"xyz",9)));
         test(new B(), new C()); // (B, C)
     }

As you can see, here the types don't need to match exactly, but 
they need to have a common base type.


More information about the Digitalmars-d-learn mailing list