Инициализировать константный объект вне конструктора

В следующем коде:

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

Я бы хотел, чтобы класс B мог вызывать только методы const или immutable из A. Однако B может создать экземпляр A только после того, как он уже создан, поэтому нет возможности инициализировать A в конструкторе. Могу ли я исправить приведенный выше код, не удаляя const из переменной a?


d dmd
person glampert    schedule 10.07.2014    source источник


Ответы (1)


Используйте 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();
    }
}
person user3824090    schedule 10.07.2014