Skip to content

Instantly share code, notes, and snippets.

@JakobOvrum
Last active December 26, 2015 14:19
Show Gist options
  • Save JakobOvrum/7165288 to your computer and use it in GitHub Desktop.
Save JakobOvrum/7165288 to your computer and use it in GitHub Desktop.
Demonstration of template pattern matching
// Takes instances of `Foo`
struct Foo(T){ T t; }
string takesFoo(T)(T t) if(is(T == Foo!U, U))
{
static if(is(T == Foo!U, U))
return U.stringof;
else
static assert(false);
}
immutable foo = takesFoo((Foo!int).init);
static assert(foo == "int");
// Takes any templated type
struct Bar(T, U) {}
string takesAny(T)(T t)
{
import std.string : format;
static if(is(T == U!Args, alias U, Args...))
return "T is %s!%s".format(__traits(identifier, U), Args.stringof);
}
immutable bar = takesAny(Bar!(int, float).init);
static assert(bar == "T is Bar!(int, float)");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment