Created
December 9, 2013 22:03
-
-
Save JakobOvrum/7881811 to your computer and use it in GitHub Desktop.
Approximation of C#'s `using` statement in D
This file contains 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
interface IDisposable | |
{ | |
void dispose(); | |
} | |
auto using(T : IDisposable, CtorArgs...)(auto ref CtorArgs ctorArgs) | |
if(is(T == class) && __traits(compiles, new T(ctorArgs))) | |
{ | |
static struct Result | |
{ | |
private T obj; | |
inout(T) using_Result_get() inout @property | |
{ | |
return obj; | |
} | |
alias using_Result_get this; | |
~this() | |
{ | |
obj.dispose(); | |
} | |
} | |
return Result(new T(ctorArgs)); | |
} | |
class Test : IDisposable | |
{ | |
string value; | |
bool disposed = false; | |
this(string value) | |
{ | |
this.value = value; | |
} | |
override void dispose() | |
{ | |
disposed = true; | |
} | |
} | |
Test test() | |
{ | |
// Fancy way of saying: | |
// auto obj = new Test("test"); | |
// scope(exit) obj.dispose(); | |
auto obj = using!Test("test"); | |
assert(obj.value == "test"); | |
assert(!obj.disposed); | |
return obj; | |
} | |
void main() | |
{ | |
auto obj = test(); | |
assert(obj.disposed); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment