簡體   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