在D中组合不可变和普通的构造函数?

Sci*_*llo 4 d immutability

是否可以编写一个构造函数而不是两个,仍然能够创建普通和不可变对象?编写普通和不可变构造函数需要做很多重复工作.

class ExampleClass
{
    void print() const
    {
        writeln(i);
    }

    this(int n)
    {
        i = n * 5;
    }

    this(int n) immutable
    {
        i = n * 5;
    }

private:
    int i;
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*ppe 7

创建构造函数pure,它可以隐式转换为任何限定符.

this(int n) pure
{
    i = n * 5;
}

auto i = new immutable ExampleClass(2);
auto m = new ExampleClass(3);
Run Code Online (Sandbox Code Playgroud)

记录在这里:http: //dlang.org/class.html "如果构造函数可以创建唯一对象(例如,如果它是纯粹的),则该对象可以隐式转换为任何限定符."

BTW:其他纯函数的返回值也隐式转换.

// returns mutable...
char[] cool() pure {
    return ['c', 'o', 'o', 'l'];
}

void main() {
    char[] c = cool(); // so this obviously works
    string i = cool(); // but since it is pure, this works too
}
Run Code Online (Sandbox Code Playgroud)

在那里工作的原则相同,它是独一无二的,因此可以假设它是共享的或不可变的.