原文
我正在试实现
替代的基础库,来避免模板/mixin/static/traits
代码,只为了:使得更容易解析"智能感知"
代码.
我需要"泛型"
,但D没有泛型
:我按"最简单"
方式使用模板.
即:
interface IIterable(T)
{
bool empty();
void popFront();
T front();
}
IIterable!S toIterable(S)(S[] source)
=> new ArrayIterable!S(source);
IIterable!S filter(S)(IIterable!S source, bool delegate(S item) predicate)
=> new Filter!S(source, predicate);
IIterable!S filter(S)(S[] source, bool delegate(S item) predicate)
=> toIterable(source).filter(predicate);
//...
然后,在main.d
中,我:
import std.stdio;
void main(){
[1,2,3,4,5,6].toIterable!int.filter!int(i=>i%2==0).map!int(i=>i*2).toArray.writeln();
}
它工作正常,直到我从过滤(filter)
方法中删除!int
.
main.d(3,38)
:错误:"filter"
模板的重载不能使用参数类型"!()(IIterable!int,void)'
.
iterable.d(21,13)
:候选者为:
filter(S)(IIterable!S source, bool delegate(S item) predicate)
iterable.d(23,13):'filter(S)(S[]source,booldelegate(Sitem)predicate)'
基本上,它不知道要用的哪个版本
的过滤器
,因为它推导i=>i%2==0
为空(void)
?!
!()(IIterable!int, void)
如果显式写入(int i)=>i%2==0
,它会再次正确编译.
当IIterable!S source
已经是IIterable!int
,是否必须显式
告知S是int
?
这是编译器的错误/限制
.我找不到有关issues.dlang.org
的现有报告,因此提交了.
目前,最好是在λ
中指定类型
,如(int i)=>i%2==0
.
看到void
的原因是,编译器无法确定函数字面
类型时,会当作模板函数
:
static assert(__traits(isTemplate, i => i % 2 == 0));
出于愚蠢
的历史原因,编译器试确定
模板类型
时,它会返回void
而不是给出错误
:
template example() {}
static assert(is(typeof(example) == void)); //什么