scoped classes and dependency inversion
Sjoerd Nijboer
dlang at sjoerdnijboer.com
Thu Nov 8 21:16:32 UTC 2018
On Thursday, 8 November 2018 at 16:31:26 UTC, Neia Neutuladh
wrote:
> I believe what you need to do is pass a factory function into
> the constructor. This is a bit awkward.
Yep, but I want a "nice and descriptive syntax" for it.
> Anyway, here's some code to make it work. It's kind of ugly.
>
> ---
> import std.stdio;
> import std.typecons;
>
> void main()
> {
> auto bar = new Bar!Foo((ref f) { f = scoped!Foo(); });
> }
>
> class Bar(TFoo) if(is(TFoo : IFoo))
> {
> alias SFoo = typeof(scoped!TFoo());
> SFoo _foo;
> this(void delegate(ref SFoo) dg)
> {
> dg(_foo);
> }
> }
>
> class Foo : IFoo
> {
> void baz(){}
> }
>
> interface IFoo
> {
> void baz();
> }
> ---
I tried to get something more nice looking and I'm stuck on the
following.
I tried tom make a lazyscoped!T but I'm stuck at creating a
constructor and determining the arguments from the Type. If I
could do that I could just forward a lazyscoped!T which would
have my parameters encapsulated to an object and have that object
instantiate it at its place.
Maybe not the smartest idea but I think it's a little more
descriptive than using a factory lambda.
```
import std.typecons : scoped;
void main() {
auto initData = 42;
auto bar = new Bar!Foo(lazyscoped!(Foo)(initData));
}
class Bar(TFoo, TArgs...) if(is(TFoo : IFoo)) {
private typeof(scoped!TFoo()) _foo;
this(lazyscoped!TFoo foo) {
foo.construct(_foo);
}
}
class Foo : IFoo {
int orWhatTypeEver;
this(T)(T myParam) {
orWhatTypeEver = /*cast(int)*/myParam;
}
void baz(){}
}
interface IFoo{ void baz(); }
struct lazyscoped(T) {
import std.typecons : scoped;
TArgs args; // somehow determine TArgs assumimg there is only
one __ctor of type T.
this(TArgs args) {
static if(TArgs.length > 0)
this.args = args;
}
void construct(ref typeof(scoped!T()) scoped_t) {
scoped_t = scoped!T(args);
}
}```
More information about the Digitalmars-d-learn
mailing list