如何从泛型函数中调用最精确的重载?
How can I call the most precise overload from a generic function?
This guy 说 Swift 泛型方法可以重载作为一种特殊化它们的方式:
func testMethod<T: Comparable>(v: T) -> T {
return v
}
func testMethod(v: Int) -> Int {
return v * 12345
}
所以我想得到一些类似的东西。我做了一个 class 来从字节缓冲区读取整数。它特别定义了这些方法:
public func read(type: Int32.Type) -> Int32 {
return /* implementation detail */
}
public func read<T: IntegerType>(type: T.Type) -> T {
let bug: T! = nil
return bug
}
public func readInto<T: IntegerType>(inout into: T) {
into = read(T.self)
}
还有很多 read(type: [U]Int[bits])
方法可以重载 read<T>
方法。如果我尝试从非泛型实现未涵盖的类型中读取,泛型方法是一种万能的方法,会使我的程序崩溃。
readInto
方法是一种方便的方法,因此我不必重复对象的类型。如果我想读入一个 Int32
变量,而不是做 variable = reader.read(type: Int32.self)
,我可以做 reader.read(&variable)
,因为我不想重复自己,所以我觉得这样更好。
我的问题是来自 readInto
的调用会系统地转到包罗万象的 read<T>
,即使存在更精确的过载也是如此。
有没有办法让它从泛型方法中调用最精确的重载?
这不能解决一般问题,但 Swift 函数可以从它们的 return 类型重载。例如:
func foo() -> Int16 {
return 0
}
func foo() -> Int32 {
return 1
}
let i16: Int16 = foo() // 0
let i32: Int32 = foo() // 1
let i = foo() // compile-time error: ambiguous
这实际上意味着我不需要 readInto
方法来读入给定类型的变量,我可以将 read()
调用的结果分配给它并完成有了它,该死的仿制药。
This guy 说 Swift 泛型方法可以重载作为一种特殊化它们的方式:
func testMethod<T: Comparable>(v: T) -> T {
return v
}
func testMethod(v: Int) -> Int {
return v * 12345
}
所以我想得到一些类似的东西。我做了一个 class 来从字节缓冲区读取整数。它特别定义了这些方法:
public func read(type: Int32.Type) -> Int32 {
return /* implementation detail */
}
public func read<T: IntegerType>(type: T.Type) -> T {
let bug: T! = nil
return bug
}
public func readInto<T: IntegerType>(inout into: T) {
into = read(T.self)
}
还有很多 read(type: [U]Int[bits])
方法可以重载 read<T>
方法。如果我尝试从非泛型实现未涵盖的类型中读取,泛型方法是一种万能的方法,会使我的程序崩溃。
readInto
方法是一种方便的方法,因此我不必重复对象的类型。如果我想读入一个 Int32
变量,而不是做 variable = reader.read(type: Int32.self)
,我可以做 reader.read(&variable)
,因为我不想重复自己,所以我觉得这样更好。
我的问题是来自 readInto
的调用会系统地转到包罗万象的 read<T>
,即使存在更精确的过载也是如此。
有没有办法让它从泛型方法中调用最精确的重载?
这不能解决一般问题,但 Swift 函数可以从它们的 return 类型重载。例如:
func foo() -> Int16 {
return 0
}
func foo() -> Int32 {
return 1
}
let i16: Int16 = foo() // 0
let i32: Int32 = foo() // 1
let i = foo() // compile-time error: ambiguous
这实际上意味着我不需要 readInto
方法来读入给定类型的变量,我可以将 read()
调用的结果分配给它并完成有了它,该死的仿制药。