Init const对象在构造函数之外

时间:2014-07-10 03:59:12

标签: d dmd

在以下代码中:

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调用immutableA方法。但是,B只能在构造后创建A的实例,因此无法在构造函数中初始化A。我是否可以修改上述代码,而无需从var const移除a

1 个答案:

答案 0 :(得分:3)

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