繁体   English   中英

d2:使用非默认构造函数初始化时,opApply的不可变结构不会编译

[英]d2: Immutable structs with opApply do not compile when initialized with non-default constructor

考虑以下代码:

immutable struct Test {
    this(int foo) { }

    int opApply(int delegate(ref int) dg) {
        return (0);
    }
}

int main(string[] argv) {
    auto set = Test(); // compiles
    // auto set = Test(1); // Error: cannot uniquely infer foreach argument types

    foreach (item; set) { }

    return 0;
}

当使用默认的无参数构造函数构建Test结构时,代码编译得很好,但是当我尝试使用任何其他构造函数时,我得到编译时错误。 如果我注释掉foreach ,代码将编译。 如果我注释掉immutable ,代码也会编译。

这种行为的原因是什么以及如何解决?

实际上,至少使用DMD版本2.059,它不能使用任何构造函数进行编译(在Windows 7和FreeBSD上测试)。

其原因应该是相当明显的。 通过使结构(或类)不可变,您只需将不可变应用于该结构(或类)的每个成员。 但是,构造函数不会变为不可变。 也就是说,当您声明immutable struct Test您已经有效地完成了以下操作:

struct Test {
    this(int foo) { }
    immutable int opApply(int delegate(ref int) dg) {
        return (0);
    }
}

注释掉foreach循环允许代码编译,因为foreach正在寻找没有immutable声明的opApply方法。

根据你想要做的事情,你可以简单地使结构final而不是immutable ,或者,如果你想保持你的大部分结构不可变...

struct Test {
    // Anything that needs to be mutable should go up here
    int opApply(int delegate(ref uint) dg) {
        return 0;
    }

    // Anything put in this block is immutable
    immutable {
        this(int foo) { }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM