Last active
December 26, 2015 14:19
-
-
Save JakobOvrum/7165288 to your computer and use it in GitHub Desktop.
Demonstration of template pattern matching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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