在D2中使用带有成员函数的std.algorithm.map [英] Using std.algorithm.map with member functions in D2

查看:125
本文介绍了在D2中使用带有成员函数的std.algorithm.map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

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));
  }
}

但是你当然不能这样做, code> getBar 取决于这个参数,这将超出范围。如果您尝试创建本地函数委托,则同样适用。我还考虑用 opCall 创建一个函数对象,但不能使用 map (可以吗?)

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?).

一些要求:


  • 返回的范围必须是懒惰的(所以没有

  • 假设 getBar 是获取数据的唯一方法。

  • 我希望地图由类封装(即不将地图移动到调用站点)。

  • 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).

推荐答案

std.algorithm.map 通过模板别名参数工作,绑定在编译时。在这些情况下,Walter Bright(D语言设计师)尚未明确说明模板别名参数的语义,尽管您试图做的似乎是以某种方式在实践中工作。澄清这是一个todo(我想)。也许你会更好地在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.

这篇关于在D2中使用带有成员函数的std.algorithm.map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆