(更新:我添加了一个重现示例)
代码如下所示:
type Lib =
static member inline tryMe (a: ^a) =
let name = (^a: (static member name: string) ())
name
type Test =
struct
val Value: string
new v = {Value = v}
end
static member inline name with get() = "HiThere"
static member works(a:Test) = Lib.tryMe a
这将“正常工作”并编译。但是,如果你稍微扩展一下,例如如下所示:
/// Does a bounds check and raises an error if bounds check is not met
let inline checkBounds f (g: 'b -> ^c) (tp: ^a) =
let convertFrom = (^a: (static member name: string) ())
let convertTo = (^c: (static member name : string) ())
let value = (^a: (member Value: 'b) tp)
if f value then
g value
else
failwithf "Cannot convert from %s to %s." convertFrom convertTo
type ConverterA =
struct
val Value: sbyte
new v = { Value = v }
end
static member inline name with get() = "converter-a"
static member inline convert (x: ConverterA) : ConverterB =
checkBounds ((>=) 0y) (byte >> ConverterB) x
and ConverterB =
struct
val Value: byte
new v = { Value = v }
end
static member inline name with get() = "converter-b"
它会引发一大堆虚假的 FSharp 编译器错误。
错误 FS1114:值“Foo.Bar.name”已标记
内联但未绑定在优化环境中
错误 FS1113:值“名称”被标记为内联,但其
实现使用内部或私有函数,该函数不是
足够容易到达
警告 FS1116:标记为“内联”的值具有意外值
错误 FS1118:无法内联值“名称”
标记为“内联”,可能是因为递归值被标记为“内联”
我还没有看到其他内联函数发生这种情况。我不确定这里会发生什么。如果我稍微改变一下,例如删除convertTo
line 及其依赖项,它编译得很好。
在 FSI 中运行代码时,即使使用 FSI 设置,也不会出现错误--optimize
.
我可以通过删除来解决这个问题inline
。对于这种类型的字段来说,这并不重要,JIT 会内联它们,即使 F# 没有。
这是编译器错误吗?或者我的代码中是否存在错误,或者我没有意识到对显式成员约束的某些限制?
您需要重新排序,以便您使用的函数在使用时就已知,否则 F# 编译器似乎不知道要内联什么。正如您在下面的评论中所说,如果您问我,这个答案就是一个错误。
/// Does a bounds check and raises an error if bounds check is not met
let inline checkBounds f (g: 'b -> ^c) (tp: ^a) =
let convertFrom = (^a: (static member name: string) ())
let convertTo = (^c: (static member name : string) ())
let value = (^a: (member Value: 'b) tp)
if f value then
g value
else
failwithf "Cannot convert from %s to %s." convertFrom convertTo
type ConverterB =
struct
val Value: byte
new v = { Value = v }
end
static member inline name with get() = "converter-b"
and ConverterA =
struct
val Value: sbyte
new v = { Value = v }
end
static member inline name with get() = "converter-a"
static member inline convert (x: ConverterA) : ConverterB =
checkBounds ((>=) 0y) (byte >> ConverterB) x
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)