cool pattern matching template

Vlad Levenfeld via Digitalmars-d digitalmars-d at puremagic.com
Thu Jan 1 14:21:07 PST 2015


On Thursday, 1 January 2015 at 19:54:56 UTC, Phil wrote:
> Could you give a concrete example of using your Match template?
>
> e.g. to perform a different action for floating point or 
> integral values.
>

   auto f (T)(T n)
   {
      auto integral ()() {return integral_only_func (n);}
      auto floating_point ()() {return float_func (n);}

      return Match!(integral, floating_point);
   }

Assuming the integral_only_func rejects floating point numbers, 
then Match will attempt the integral version first and, if it 
fails, fall back on float_func.

Matching an explicitly defined list of patterns, as above, is the 
most common way I use it, though some more interesting examples 
come up from time to time.

Here's an example from a project of mine, using Match in-line to 
deduce the length of some vertex arrays attached to an openGL 
shader struct. It assumes all attached arrays have the same 
length. The template constraint prevents accidentally grabbing 
the length of a uniform vector argument.

   template length (uint i)
   {
     auto length ()() if (not (is (typeof(shader.args[i]) == 
Vector!U, U...)))
       {return shader.args[i].length.to!int;}
   }

   gl.DrawArrays (shader.mode, 0, Match!(Map!(length, 
Count!(Shader.Args))));

(where Count!T means staticIota!(0, T.length) and Map is an alias 
of staticMap)


More information about the Digitalmars-d mailing list