在 D2 中将 std.algorithm.map 与成员函数结合使用

发布于 2024-09-25 12:57:38 字数 698 浏览 3 评论 0原文

我有:

Foo foo = new Foo();

foreach (i; 0..10)
{
  Bar bar = foo.getBar(i);
  ...
}

我希望能够(等效地)说:

foreach (bar; foo.getAllBars())
{
  ...
}

我如何去实现getAllBars()

我想了这样的事情:

class Foo
{
  auto getAllBars()
  {
    return map!(getBar)(iota(10));
  }
}

但是你当然不能这样做,因为 getBar 依赖于 this 参数,这将超出范围。如果您尝试创建本地函数委托,同样适用。我还考虑过使用 opCall 创建函数对象,但您不能将它们与 map 一起使用(可以吗?)。

一些要求:

  • 返回的范围必须是惰性的(因此不能先将其复制到数组中)
  • 假设 getBar 是获取数据的唯一方法。
  • 我希望地图由类封装(即不将地图移动到调用站点)。

I have:

Foo foo = new Foo();

foreach (i; 0..10)
{
  Bar bar = foo.getBar(i);
  ...
}

I want to be able to instead say (equivalently):

foreach (bar; foo.getAllBars())
{
  ...
}

How do I go about implementing getAllBars()?

I figured something like this:

class Foo
{
  auto getAllBars()
  {
    return map!(getBar)(iota(10));
  }
}

But you can't do that of course because getBar depends on the this parameter, which will go out of scope. The same applies if you try to create a local function or delegate. I also considered creating a function object with opCall, but you can't use those with map (can you?).

Some requirements:

  • The returned range must be lazy (so no copying it into an array first)
  • Assume that getBar is the only way to get at the data.
  • I want the map to be encapsulated by the class (i.e. no moving the map to the call site).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

找个人就嫁了吧 2024-10-02 12:57:38

std.algorithm.map 通过模板别名参数工作,并在编译时进行绑定。 Walter Bright(D 语言设计者)尚未清楚这些情况下模板别名参数的语义,尽管您尝试做的事情似乎不知何故在实践中有效。澄清这一点是待办事项(我认为)。也许您最好在 digitalmars.d 新闻组上询问这个问题,因为这会引起 Walter 的注意并鼓励他澄清语义。

std.algorithm.map works via a template alias parameter, and binding is at compile time. Walter Bright (the D language designer) hasn't been clear yet on the semantics of template alias parameters in these situations, though what you're trying to do seems to somehow work in practice. Clarifying this is a todo (I think). Perhaps you would be better off asking this on the digitalmars.d newsgroup, as this would get Walter's attention and encourage him to clarify the semantics.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文