在 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));
}
}
但是你当然不能这样做,因为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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.