Template specialisation for range of types

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Mar 12 13:04:06 PDT 2017


data pulverizer wrote:

> If I change the implementation of the second template to your above 
> declaration, I get the error:
>
> max.max called with argument types (const(double)*, const(double)*) 
> matches both:
> max.d(34):     max.max!(const(double)*).max(const(double)* x, 
> const(double)* y)
> and:
> max.d(42):     max.max!double.max(const(double)* x, const(double)* y)
>
> I need at least those two implementation for the different cases, a 
> general "default", and for specified types and type qualifications.

'cause your templates are for different types, so they both matches. i 
wrote only about type deconstruction. the following will work:

  import std.stdio : writeln;
  import std.traits : Unqual;

  auto max(T)(T* x, T* y) if (is(T == Unqual!T)) {
    writeln("General template");
    return *x > *y ? x : y;
  }

  auto max(T)(T* x, T* y) if (is(T == const)) {
    writeln("Const template");
    return *x > *y ? x : y;
  }


  void main () {
    const double p = 2.4, q = 3;
    writeln(max(&p, &q));
  }

note the change in the first template.


More information about the Digitalmars-d-learn mailing list