Windows bindings
Rumbu
rumbu at rumbu.ro
Fri Feb 19 12:16:41 UTC 2021
On Wednesday, 17 February 2021 at 14:49:58 UTC, Steven
Schveighoffer wrote:
> On 2/16/21 4:48 PM, Elronnd wrote:
What do you think?
//Usage:
@RAIIFree!CloseHandle
struct SomeHandle
{
ptrdiff_t value;
}
SomeHandle CreateSomeHandle(int x, int y);
void DoSomethingWithSomeHandle(Handle h);
void CloseSomeHandle(SomeHandle h);
auto h = autoFree(CreateSomeHandle(42, 666));
DoSomethingWithSomeHandle(h);
//Implementation
struct RAIIFree(alias H)
{
private alias Handler = H;
}
auto autoFree(T)(T handle)
{
return RAIIWrapper!(T, FreeFunctionOf!T)(handle);
}
struct RAIIWrapper(Handle, alias CloseHandler)
{
Handle s;
alias s this;
@disable this();
@disable this(this);
this(Handle value)
{
this.s = value;
}
~this()
{
CloseHandler(s);
}
}
private template FreeFunctionOf(T, A...)
{
static if (A.length == 0)
{
alias attrs = __traits(getAttributes, T);
static assert(attrs.length > 0, T.stringof ~ " doesn't
have any attribute attached to it");
alias FreeFunctionOf = FreeFunctionOf!(T, attrs);
}
else static if (A.length == 1)
{
static assert(isFreeHandler!(T, A[0]), T.stringof ~ "
doesn't have a correct @RAIIFree attribute attached to it");
alias FreeFunctionOf = A[0].Handler;
}
else static if (isFreeHandler!(T, A[0]))
alias FreeFunctionOf = A[0].Handler;
else
alias FreeFunctionOf = FreeFunctionOf!(T, A[1 .. $]);
}
private template isFreeHandler(T, alias A)
{
enum isFreeHandler = is(typeof(A.Handler))
&& is(typeof(A.Handler(T.init)));
}
More information about the Digitalmars-d
mailing list