D 2015/2016 Vision?
Namespace via Digitalmars-d
digitalmars-d at puremagic.com
Wed Oct 7 04:38:18 PDT 2015
On Wednesday, 7 October 2015 at 11:27:49 UTC, Marc Schütz wrote:
> On Wednesday, 7 October 2015 at 10:03:44 UTC, Namespace wrote:
>> Because there is no guarantee that others, who use your code,
>> get it right and use those constructs.
>
> The obvious way would be to make the constructor private and
> only provide a factory method returning a Scoped!Texture2D. I
> just tried that, but ran into problems with the construction
> (probably a bug in emplace). Don't have time to investigate
> this now. Maybe you can also return a Unique!Texture2D, but
> that one doesn't have an alias this...
Something like this?
----
import std.stdio;
struct Scoped(T) if (is(T == class)) {
private void[__traits(classInstanceSize, T)] _buf = void;
this(Args...)(auto ref Args args) {
_buf = typeid(T).init[];
this.get().__ctor(args);
}
@disable
this(this);
~this() {
.destroy(this.get());
}
@nogc
private inout(T) get() inout pure nothrow {
return cast(T) _buf.ptr;
}
auto opDispatch(string method, Args...)(auto ref Args args) {
return mixin("this.get()." ~ method ~ "(args)");
}
}
class A {
private string name;
private this(string name) {
this.name = name;
writeln("Creating A");
}
static auto scoped(Args...)(auto ref Args args) {
return Scoped!(typeof(this))(args);
}
~this() {
writeln("Destroying A");
}
void hello() {
writeln("Hello, ", this.name);
}
}
void main() {
auto a = A.scoped("Foo");
a.hello();
}
----
Kinda ugly, but it works.
More information about the Digitalmars-d
mailing list