如何通过另一种类型参数约束一个类型参数 [英] How to constrain one type parameter by another

查看:22
本文介绍了如何通过另一种类型参数约束一个类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法限制一个类型参数派生自另一个?

type Foo<'T, 'U 当 'U :>'T>=成员 x.Bar() : 'T = upcast Unchecked.defaultof<'U>

此代码产生以下错误:

<块引用>

错误 1 ​​无效约束:用于约束的类型是密封的,这意味着该约束最多只能由一种解决方案来满足

错误 2 此类型参数的使用方式将其限制为始终为 ''T'

错误 3 从类型 'T 到 'T0 的静态强制涉及基于此程序点之前的信息的不确定类型.某些类型不允许静态强制.需要进一步的类型注释.

警告 4 这种结构导致代码不像类型注释所指示的那样通用.类型变量 'U 已被约束为类型 ''T'.

解决方案

No :(.这是目前 F# 最不幸的限制之一(在我看来).请参阅 解决子类型约束 规范的部分,其中指出><块引用>

表单类型的新约束:> 'b 再次求解为 type = 'b.

这真的很遗憾,否则我们可以解决 F# 缺乏通用差异的问题:

let cvt<'a,'b when 'a :>'b>(s:seq<'a>):seq<'b>=//不编译|>盒子|>拆箱

Is there a way to constrain one type parameter to be derived from another?

type Foo<'T, 'U when 'U :> 'T> = 
    member x.Bar() : 'T = upcast Unchecked.defaultof<'U>

This code produces the following errors:

Error 1 Invalid constraint: the type used for the constraint is sealed, which means the constraint could only be satisfied by at most one solution

Error 2 This type parameter has been used in a way that constrains it to always be ''T'

Error 3 The static coercion from type 'T to 'T0 involves an indeterminate type based on information prior to this program point. Static coercions are not allowed on some types. Further type annotations are needed.

Warning 4 This construct causes code to be less generic than indicated by the type annotations. The type variable 'U has been constrained to be type ''T'.

解决方案

No :(. This is one of the most unfortunate limitations of F# at the moment (in my opinion). See the Solving Subtype Constraints section of the spec, which states that

New constraints of the form type :> 'b are solved again as type = 'b.

This is really a shame since otherwise we could work around F#'s lack of generic variance:

let cvt<'a,'b when 'a :> 'b> (s:seq<'a>) : seq<'b> = // doesn't compile
  s |> box |> unbox

这篇关于如何通过另一种类型参数约束一个类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆