Using std.algorithm.map with member functions in D2

心不动则不痛 提交于 2019-12-22 10:11:15

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/3848173/using-std-algorithm-map-with-member-functions-in-d2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!