October 25, 2019 Template type deduction and specialization works on template alias parameters | ||||
---|---|---|---|---|
| ||||
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; } ``` |
Copyright © 1999-2021 by the D Language Foundation