DIP 1023--Resolution of Template Alias Formal Parameters in Template Functions--Community Review Round 1

jmh530 john.michael.hall at gmail.com
Mon Sep 30 19:16:47 UTC 2019


On Wednesday, 11 September 2019 at 22:30:31 UTC, Stefanos 
Baziotis wrote:
> [snip]

Another example of where something like what I had suggested 
above with constrained aliases might be useful.

For whatever dumb reason, I was just playing around with 
restricting Algebraic to only allow numeric types. You have to 
create a new struct and add in some member functions to get it to 
work. You can do more-or-less the same thing with an alias, 
easier IMO, but then if a function calling that alias doesn't 
work as easily (for reasons discussed above in thread).

import std.variant;
import std.traits : isNumeric;
import std.meta : allSatisfy;

struct Foo(T...)
     if (allSatisfy!(isNumeric, T))
{
     Algebraic!(T) x;
     alias x this;

     this(U)(U val) {
         x = val;
     }

     void opAssign(U)(U val) {
         x = val;
     }
}

template Bar(T...)
     if (allSatisfy!(isNumeric, T))
{
     alias Bar = Algebraic!(T);
}

void useFoo(T...)(Foo!T x) {

}

void useBar(T...)(Bar!T x) {

}

void main() {
     import std.stdio : writeln;

     auto v = Foo!(int, double)(5);
     writeln(v.peek!(int));
     writeln(v);
     v = 3.14;
     writeln(v.peek!(double));
     writeln(v);

     auto w = Bar!(int, double)(5);

     useFoo(v);
     //useBar(w); //does not compile currently
}


More information about the Digitalmars-d mailing list