d - 在构造函数之外初始化 const 对象

标签 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 只能从 A 调用 constimmutable 方法。但是,B 只能在构造完成后才能创建 A 的实例,因此无法在构造函数中初始化 A。我可以在不从 var a 中删除 const 的情况下修复上面的代码吗?

最佳答案

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

关于d - 在构造函数之外初始化 const 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24668243/

相关文章:

operator-overloading - 为什么 opAssign 不能为类重载?

d - 为什么 int x=08;当 int x=078 时有效;在 `DMD` 中无效?

class - struct vs class 用于围绕外语编写 D 包装器

d - to!string(enum.member) 如何工作?

d - 我可以指定最小配音或 DMD 版本吗?

d - 如何轻松地初始化函数指针?

c++ - 如何正确从 D 接口(interface)到 C++?

garbage-collection - D 垃圾收集器 - 估计运行频率和运行时长?

D 编程语言 : module stdio cannot read file std\stdio. d

d - 创建用户定义的不可变对象(immutable对象)