gpt4 book ai didi

d - 在 D 中将成员函数作为模板参数传递

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

我创建了一个实现阿特金筛子来寻找素数的类。该类存储结果并提供“isPrime”方法。我还想添加一个允许您迭代素数的范围。我在想这样的事情:

@property auto iter() { return filter!(this.isPrime)(iota(2, max, 1)); }

不幸的是,这不起作用:

Error: function primes.primes.isPrime (ulong i) is not callable using argument types ()
Error: expected 1 function arguments, not 0

没有我得到的“这个”

Error: this for isPrime needs to be type primes not type Result

有没有办法将成员函数作为模板参数传递?

最佳答案

您不能对模板参数使用方法(委托(delegate)),因为它们需要一个上下文,而这在编译时是未知的。

您可以使 isPrime 成为静态方法或自由函数(然后删除 this. 并且您的代码将起作用),或者(如果该方法故意不是静态的),使用匿名委托(delegate)文字:

@property auto iter() { return filter!((x) { return isPrime(x); })(iota(2, max, 1)); }

在 2.058 中,您将能够编写:

@property auto iter() { return filter!(x => isPrime(x))(iota(2, max, 1)); }

关于d - 在 D 中将成员函数作为模板参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8911182/

25 4 0
文章推荐: file-upload - 带有图像检测功能的纯ASP上传
文章推荐: open-source - 让开源项目拥有贡献者的一些好的做法是什么?
文章推荐: asp.net - ASP :Login always generates a ,如何使其停止?