How do you use templates in D?

Graham Fawcett fawcett at uwindsor.ca
Tue Oct 18 12:48:11 PDT 2011


On Tue, 18 Oct 2011 15:06:21 -0400, Andrew Pennebaker wrote:

> Recap:
> 
> forAll() accepts a property of type bool function(void), and a
> collection of generator functions, of types *arbitrary_type*
> function(void). forAll calls the generator functions, storing the values
> in another collection, and passing the values to the property. If the
> property returns false, the values are printed to the screen.

A variadic forAll seems doable, e.g.

  forAll!isEven(&my_ints, &my_floats, &my_ulongs);

The types are not *entirely* arbitrary, right? Each has a return type Tn, 
constrained such that "isEven!Tn" must be a valid instance of the isEven 
template. so "forAll!isEven(&ints, &floats, &bananas)" would be invalid, 
assuming there's no legal "isEven!Banana" instance.

It would look something like this (here with arrays, instead of lambdas):

import std.stdio;

bool isEven(T)(T v) {
  return v % 2 == 0;
}

bool forAll(alias Pred, T...)(T seqs) {
  bool result = true;
  foreach(sequence; seqs) {
    foreach(elem; sequence)
      result &= Pred(elem);
  }
  return result;
}

void main() {
  writeln(forAll!isEven([22, 22], [23L, 22L]));
  writeln(forAll!isEven([2,4], [6.0,8.0], [10L,12L]));
} 

Graham



More information about the Digitalmars-d mailing list