首頁>Program>source

是否有一種方法可以約束一个型別引數从另一个引數派生?

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

此代碼产生以下錯誤:

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

15

f#

最新回復
  • 6月前
    1 #

    No:(。。(目前我认為)這是F#最不幸的限製之一。請參阅規範的"解決子型別約束"部分,其中指出

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

    這真的很遗憾,因為否則我们可以解決F#缺少通用方差的問题:

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

  • windows:批處理指令碼中的符號^是什麼意思?
  • c++:在针對C ++ 03時,將std :: basic_string <t>用作连續緩衝區是否合理?