Template type deduction and specialization works on template alias parameters
Superstar64
Hexagonalstar64 at gmail.com
Fri Oct 25 06:13:42 UTC 2019
I just wanted to make this post to showcase that template type
deduction and template specialization works on templates alias
parameters and give an example of what this could possibly be
used for.
```
struct Identity(A)
{
A get;
}
f!B fmap(alias f : Identity, A, B)(B delegate(A) callback, f!A
functor)
{
return Identity!B(callback(functor.get));
}
struct Array(A)
{
A[] get;
}
f!B fmap(alias f : Array, A, B)(B delegate(A) callback, f!A
functor)
{
B[] result = new B[functor.get.length];
foreach (c, ref x; result)
{
x = callback(functor.get[c]);
}
return Array!B(result);
}
f!int square(alias f)(f!int functor)
{
return fmap((int x) => x * x, functor);
}
void main()
{
import std.stdio;
auto one = fmap((int a) => a + 1, Identity!int(0));
auto numbers = fmap((int a) => a + 1, Array!int([1, 2, 3]));
one.writeln;
numbers.writeln;
Identity!int(4).square.writeln;
Array!int([1, 2, 3]).square.writeln;
}
```
More information about the Digitalmars-d
mailing list