On Thu, 08 Nov 2018 11:04:19 +0000, Sjoerd Nijboer wrote:
> I'm trying to invert the dependency from the classes `Bar -> Foo` to
> `Foo -> IFoo <- Bar` at compile time.
> 
> I do want `Foo's` to be embedded into `Bar`

These goals are a *little* at odds with each other; having a scoped!Foo 
puts significant constraints on how to build the object. But you know your 
needs a lot better than some generic advice.

I believe what you need to do is pass a factory function into the 
constructor. This is a bit awkward.

The really annoying part is that std.typecons doesn't have a named type 
for the scoped wrapper for a type. It's actively hostile to having scoped 
fields for no discernable reason. Filed https://issues.dlang.org/
show_bug.cgi?id=19379

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();
}
---

Reply via email to