1

考虑以下代码:

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,代码也会编译。

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

4

1 回答 1

3

实际上,至少使用 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 方法。

根据您要执行的操作,您可以简单地制作 structfinal而不是immutable,或者,如果您想保持大部分 struct 不可变...

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) { }
    }
}
于 2012-04-24T17:46:48.227 回答