constants - D 中的 const/ref 问题

标签 constants d

我正在尝试在 D 中实现我自己的范围,但我遇到了问题 .front()方法。
编辑:
我需要返回值是 来自 ref .

  • 如果我成功了 const ,那么返回的对象将是一个副本,这不是我想要的。
  • 如果我不成功 const ,那我就不能用 .frontconst我的范围的副本。

  • 我该如何解决这个问题?
    struct MyRange(T)
    {
        T[] buf;
    
        @property ref T front() { return this.buf[0]; }  // No error, but not const
        @property ref T front() const { return this.buf[0]; }  // Errors
        @property T front() const { return this.buf[0]; }  // No error, but a copy
        
        // Can't have all three
    }
    

    最佳答案

    尝试这个:

    struct MyRange(T)
    {
        T[] buf;
    
        @property ref T front() { return this.buf[0]; }
        @property ref const(T) front() const { return this.buf[0]; }
    }
    

    您示例中的问题是您制作了 front const 而不是返回的值,编译器不会让你像这样转义对 const 数据的可变引用。

    现在,我要指出的是,一般而言,您不应该期望 const 范围能够很好地工作。就其本质而言,它们需要可变才能迭代它们(因为您不能在常量范围内调用 popFront),因此除了使用 front 之外,您将无法做太多事情。和 empty具有常量范围。如果您可以将 const 范围隐式转换为 tail-const 范围,情况就不会那么糟糕,但这仅适用于数组,而且还没有人想出一种使用通用范围的好方法。所以不幸的是,const 范围在这一点上基本上是无用的。

    关于constants - D 中的 const/ref 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6976019/

    相关文章:

    c - 编译器在转换整型常量时做什么?

    c++ - Win32 向其他进程发送同步事件

    c++ - 继承的 const 属性和初始化(错误?)

    c++ - 模板转换运算符,需要 'const' 关键字

    c++ - const在返回类型中使用时如何影响函数

    string - 从字符串中删除给定字符(D语言)

    floating-point - 为什么 float 和 double 不在控制台上打印?

    d - 具体类数组与接口(interface)数组不协变

    compiler-construction - 数字火星 D 编译器;获取 ASM 输出

    c++ - 在可变参数构造函数中初始化 const 数组