Search code examples
ddmd

Init const object outside the constructor


In the following code:

class A
{
    void aMethod() { }
    void aConstMethod() const { }
}

class B
{
    const A a; // Not initialized in the constructor, but at a latter time

    void initA()
    {
        a = new A(); // Error: can only initialize const member 'a' inside constructor
    }

    void doStuff()
    {
        //a.aMethod(); shouldn't be allowed to call this here, B can only read from A.
        a.aConstMethod();
    }
}

I would like class B to only be able to call const or immutable methods from A. However, B can only create an instance of A after it has already been constructed, so no chance of initializing A in the constructor. Can I fix the code above without removing const from var a?


Solution

  • Use std.typecons.Rebindable:

    class A
    {
        void aMethod() { }
        void aConstMethod() const { }
    }
    
    class B
    {
        import std.typecons: Rebindable;
    
        Rebindable!(const A) a; // Not initialized in the constructor, but at a latter time
    
        void initA()
        {
            a = new A(); // Error: can only initialize const member 'a' inside constructor
        }
    
        void doStuff()
        {
            static assert(!__traits(compiles, a.aMethod())); // shouldn't be allowed to call this here, B can only read from A.
            a.aConstMethod();
        }
    }