Template specialisation for range of types
Meta via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Mar 12 13:15:43 PDT 2017
On Sunday, 12 March 2017 at 18:49:22 UTC, data pulverizer wrote:
> Hello all,
>
> I am attempting to write templates for differently qualified
> types using specialisations. Below is an example for const and
> non-const outlining my approach:
>
>
> ``````````````````````````
> import std.stdio : writeln;
> import std.traits : ConstOf;
>
> auto max(T)(T x, T y)
> {
> writeln("General template");
> return x > y ? x : y;
> }
>
>
> auto max(T: ConstOf!U, U)(T* x, T* y)
> {
> writeln("Const template");
> return *x > *y ? x : y;
> }
>
>
> void main(){
> const double p = 2.4, q = 3;
> writeln(max(&p, &q));
> }
> ``````````````````````````
>
> I get this output:
>
> General template
> 7FFE5B3759A8
>
>
> In this case would like to use the ConstOf specialisation
> instead of the default implementation for the inputs which are
> const.
>
> Thanks for you answers in advance
You need to make one little change for this to work:
import std.stdio : writeln;
import std.traits : ConstOf;
auto max(T)(T x, T y)
{
writeln("General template");
return x > y ? x : y;
}
auto max(T: const U, U)(T* x, T* y) <----- Changed `ConstOf!U` to
`const U`
{
writeln("Const template");
return *x > *y ? x : y;
}
void main(){
const double p = 2.4, q = 3;
writeln(max(&p, &q)); //Prints "Const template"
}
The reason this doesn't work is when you use ConstOf!U, it's not
looking for a `const U`, it's looking for the type `ConstOf!U`.
I'm not sure if this is a bug or not... Anyway, this will also
work if we change the following:
void main(){
ConstOf!double p = 2.4, q = 3; <----- Changed `const double` to
`ConstOf!double`
writeln(max(&p, &q)); //Prints "Const template"
}
More information about the Digitalmars-d-learn
mailing list