【发布时间】:2018-09-10 22:20:43
【问题描述】:
我有一个使用Algebraic 编写的自定义Option 类型。
struct None{};
struct Some(T){
T t;
alias t this;
T get(){
return t;
}
};
alias Option(T) = Algebraic!(Some!(T), None);
Option!T some(T)(T t){
return Option!T(Some!T(t));
}
Option!T none(T)(){
return Option!T(None());
}
然后我尝试写一些基本的便利函数:
T getValue(T,uint size)(VariantN!(size, Some!T, None) opt){
return opt.get!(Some!T).t;
}
bool isDefined(T, uint size)(VariantN!(size, Some!T, None) opt){
return opt.convertsTo!(Some!T);
}
A match(A,T,uint size)(VariantN!(size, Some!T, None) opt, A delegate(T) some, A delegate() none){
if(opt.isDefined!(T,size)){
return some(opt.getValue!(T,size));
}else{
return none();
}
}
当调用match 编译器无法为模板推断出正确的参数时:
Option!int test = some(1);
bool boolReturn = test.match((x) => false, () => true);
有错误:
Error: template util.match cannot deduce function from argument types !()(VariantN!(4LU, Some!int, None), void, bool function() pure nothrow @nogc @safe), candidates are:
src/util.d(79,3): util.match(A, T, uint size)(VariantN!(size, Some!T, None) opt, A delegate(T) some, A delegate() none)
错误输出表明match 的第二个参数(意思是bool delegate(int) 或(x) => false)被推导出为void。为什么?
这个例子可以编译(都一样,但是 x 的类型是明确给出的):
Option!int test = some(1);
bool boolReturn = test.match((int x) => false, () => true);
【问题讨论】:
标签: templates d type-inference