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

发布于 2024-12-27 13:28:22 字数 493 浏览 2 评论 0原文

我创建了一个类,它实现了阿特金筛法来查找素数。该类存储结果并提供“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

没有“this”我得到

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

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

I created a class which implements the Sieve of Atkin to find primes. The class stores the results and provides an "isPrime" method. I would like to also add a range which allows you to iterate over the primes. I was thinking of something like this:

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

Unfortunately this doesn't work:

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

without the "this" I get

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

Is there any way to pass a member function as a template argument?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落叶缤纷 2025-01-03 13:28:22

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

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

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

You can't use methods (delegates) for template parameters, because they need a context, which is not known at compile-time.

You can either make isPrime a static method or free function (then remove this. and your code will work), or (if the method is not static on purpose), use an anonymous delegate literal:

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

In 2.058 you'll be able to write:

@property auto iter() { return filter!(x => isPrime(x))(iota(2, max, 1)); }
ぶ宁プ宁ぶ 2025-01-03 13:28:22

您需要传递函数的地址,否则编译器认为您想使用 0 参数调用该函数,然后传递结果

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

you need to pass the address of the function otherwise the compiler thinks you want to call the function with 0 args and then pass the result

@property auto iter() { return filter!(&isPrime)(iota(2, max, 1)); }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文