gpt4 book ai didi

map - 在 D2 中将 std.algorithm.map 与成员函数一起使用

转载 作者:行者123 更新时间:2023-12-03 21:56:56 25 4
gpt4 key购买 nike

我有:

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参数,这将超出范围。如果您尝试创建本地 function,这同样适用或 delegate .我还考虑用 opCall 创建一个函数对象, 但你不能用 map (你可以吗?)。

一些要求:
  • 返回的范围必须是惰性的(因此不要先将其复制到数组中)
  • 假设 getBar是获取数据的唯一方法。
  • 我希望 map 被类封装(即不将 map 移动到调用站点)。
  • 最佳答案

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

    关于map - 在 D2 中将 std.algorithm.map 与成员函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3848173/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com