D - 'dup cannot deduce function' 当在 'const' 属性 内使用时

D - 'dup cannot deduce function' when used inside 'const' property

考虑以下代码:

class Bar
{
}
class Foo
{
    private: 
        Bar[] bars_;
    public:
        Bar[] bars() const @property { return bars_.dup; }
}
void 
main()
{
    auto f = new Foo();
}

目的是要有一个 Bar 的只读数组。但是,这不会编译。编译失败

template object.dup cannot deduce function

如果删除 const 限定符,它可以正常编译,但我真的想保留它 - 它确实属于那里。我试过使用 bars_.dup!Bar 代替,但这没有任何改变。我显然做错了什么 - DMD、LDC 和 GDC 都显示相同的行为 - 但我不知道是什么。

你必须在那里做某种深层复制。对于 const class,这意味着 _bars 也是常量...这意味着 Bar 也是常量。它一直是 const。

dup函数只做浅拷贝。它使用对内部对象的新引用复制数组,但不复制对象本身。所以 dup,虽然是一个新的可变数组,但仍然指向相同的 const 对象,所以它不会让你将它转换为 Bar[],只能转换为 const(Bar)[].

The intent is to have a read-only array of Bars.

这是我的做法:

const(Bar[]) bars() const @property { return bars_; }

只是 return 现有引用而不复制它,但在 return 值上将其标记为常量。

带括号的第一个 const 包含 return 值,下一个 const 包含 this 引用。两者你应该得到你想要的。