代码之家  ›  专栏  ›  技术社区  ›  Peter Alexander

如何初始化D2中的常量值数组?

  •  4
  • Peter Alexander  · 技术社区  · 15 年前

    基本上,我希望能够做到这样:

    struct Foo
    {
      const(int)[2] ints;
    
      this(int x, int y)
      {
        ints = [x, y];
      }
    }
    

    ints 是不可变的。

    如何初始化数组?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Michal Minich    15 年前

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

    const是只读视图,因此构造函数创建可变视图 i2

    第二种方法是 ints 可变和私有,然后提供公共访问器功能:

    struct Foo {
    
      private int[2] _ints;
    
      this(int x, int y) {
          _ints = [x, y];
      }
    
      @property ref const(int)[2] ints () {
          return _ints;
      }
    }
    

    编译器可以内联它。