Skip to content

Instantly share code, notes, and snippets.

@JakobOvrum
Created December 9, 2013 22:03
Show Gist options
  • Save JakobOvrum/7881811 to your computer and use it in GitHub Desktop.
Save JakobOvrum/7881811 to your computer and use it in GitHub Desktop.
Approximation of C#'s `using` statement in D
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