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

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

问题描述

是否有一种方法可以限制一个类型参数从另一个参数派生?

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>

此代码产生以下错误:

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

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

错误2该类型参数的使用方式一直使其始终为"T"

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

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

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.

警告4此构造导致代码的通用性低于类型注释所指示的通用性.类型变量'U已被约束为类型'T'.

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'.

推荐答案

否:(.这是目前F#最不幸的局限之一(我认为).请参见

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

形式为:>'b的新约束再次以type ='b的形式解决.

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

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

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天全站免登陆