gpt4 book ai didi

arrays - 如何在 D2 中初始化 const 值数组?

转载 作者:行者123 更新时间:2023-12-01 05:43:50 26 4
gpt4 key购买 nike

本质上,我希望能够做这样的事情:

struct Foo
{
const(int)[2] ints;

this(int x, int y)
{
ints = [x, y];
}
}

但这不起作用。编译器 (DMD 2.048) 只是提示 ints是不可变的。

你应该如何初始化数组?

最佳答案

一种方法是实现构造函数是这样的:

  this(int x, int y) 
{
auto i2 = cast(int[2]*)&ints;
*i2 = [x, y];
}

const 是只读 View ,因此构造函数创建可变 View i2并分配给它。我真的不喜欢第一行的强制转换,也许标准库中有一些函数封装了强制转换并从变量类型中删除了 const 修饰符,所以这可以用安全和惯用的方式表达。

第二种方法是制作 ints可变和私有(private),然后提供公共(public)访问器功能:
struct Foo {

private int[2] _ints;

this(int x, int y) {
_ints = [x, y];
}

@property ref const(int)[2] ints () {
return _ints;
}
}

编译器可能能够内联它。

关于arrays - 如何在 D2 中初始化 const 值数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3627023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com