2009-10-25 47 views
3

不能定義運算符重載的類型(?):F#動態查找操作符重載

let (?) (foo : Foo) (name : string) = foo.s + name 

let hw = foo? world 
:如果我使用的獨立讓綁定的運營商定義

type Foo = 
    val s : string 
    new(s) = { s = s } 
    static member (?) (foo : Foo, name : string) = foo.s + name 

let foo = Foo("hello, ") 
let hw = foo? world 

// error FS0043: The member or object constructor 'op_Dynamic' 
// takes 2 argument(s) but is here given 1. The required signature 
// is 'static member Foo.(?) : foo:Foo * name:string -> string'. 

一切工作正常

但我需要指定op_Dynamic運營商直接爲Foo類型。第一個代碼片段有什麼問題?

使用F# 1.9.7.4 @的Visual Studio 2010 Beta2的

回答

4

也許還有一個更簡單的方法(我會看),但是這會在緊要關頭:

type Foo =  
    val s : string  
    new(s) = { s = s }  
    static member (?)(foo : Foo, name : string) = 
     foo.s + name 

let inline (?) (o:^T) (prop:string) : ^U = 
    (^T : (static member (?) : ^T * string -> ^U)(o,prop)) 

let foo = Foo("hello, ") 
let hw = foo ? world 
printfn "%s" hw 
+2

更簡單的方法?!?是的,它的工作原理,但爲什麼我應該把這個「內聯(?)」解決方法放到任何帶重載(?)運算符的類中去使用它?爲什麼我不能直接使用定義的運算符過載? – ControlFlow 2009-10-25 18:16:11

+1

是的,事實證明F#解析器中存在一個錯誤,您的原始代碼應該可以正常工作。感謝您指出了這一點!我已經提交了這個錯誤。 – Brian 2009-10-25 18:59:52