F# member constraints + ^a byref parameters

前端 未结 3 761
执念已碎
执念已碎 2020-12-17 21:03

After some playing around F# member constraints feature and writing function like this:

let inline parse< ^a when ^a : (static member Parse: string ->          


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 21:53

    I think it is a bug too, something with member constraints and byref types. I can make a slightly less ugly reflection version by changing the signature of the member constraint:

    let inline tryParse<'a when 'a : (static member TryParse : string -> 'a byref -> bool)>  s  =
        let args = [| s ; null |]
        if typeof<'a>
            .GetMethod("TryParse", [| typeof; typeof< ^a>.MakeByRefType() |])
            .Invoke(null, args) = box true 
            then Some (args.[1] :?> 'a) 
            else None
    

    This one is very close:

    let inline tryParse< ^a when ^a: (static member TryParse: string -> ^a byref -> bool)> s =
        let mutable x = Unchecked.defaultof<'a>
        if (^a: (static member TryParse: string -> ^a byref -> bool) (s, &x))
            then Some x else None
    

    but I get a error FS0421: The address of the variable 'x' cannot be used at this point when I try to compile it.

提交回复
热议问题