F# explicit member constraints: The type variable ^T could not be generalized because it would escape its scope

后端 未结 3 1099
孤独总比滥情好
孤独总比滥情好 2020-12-07 01:45

I\'m attempting to use explicit member constraints in F#. The documentation says \"F# supports the complete set of constraints that is supported by the common language runti

3条回答
  •  抹茶落季
    2020-12-07 02:21

    You need to mark the member inline (and add type annotations if you want to force the arguments to be of type ^T):

    type MyType<'T when ^T: (static member ( + ) : ^T * ^T -> ^T)>() =   
        member inline this.F (a:^T) (b:^T)  = a + b
    

    I've also added a constructor, so that you can actually call the method:

    MyType().F 1 2
    

    As others have noted, it is rarely necessary to write out the explicit member constraints by hand since they will usually be inferred. Furthermore, in this case there's no reason to put the constraint on the type rather than the method, and having a type parameterized by a statically resolved type variable is not idiomatic.

提交回复
热议问题