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

传递成员函数作为D中的模板参数,d,D,我创建了一个类,它实现了Atkin的筛选以查找素数。该类存储结果并提供“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 () E

我创建了一个类,它实现了Atkin的筛选以查找素数。该类存储结果并提供“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
没有“这个”我得到了什么

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

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

您可以将
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));}
您需要传递函数的地址,否则编译器会认为您需要使用0个参数调用函数,然后传递结果

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