在 D 中将成员函数作为模板参数传递
我创建了一个类,它实现了阿特金筛法来查找素数。该类存储结果并提供“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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能将方法(委托)用于模板参数,因为它们需要上下文,而上下文在编译时是未知的。
您可以将
isPrime
设为静态方法或自由函数(然后删除this.
并且您的代码将正常工作),或者(如果该方法不是有意静态的),使用匿名委托文字:在 2.058 中,您将能够编写:
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 removethis.
and your code will work), or (if the method is not static on purpose), use an anonymous delegate literal:In 2.058 you'll be able to write:
您需要传递函数的地址,否则编译器认为您想使用 0 参数调用该函数,然后传递结果
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