2

我有一个带有一个通用参数的基本函数:

let func<'T> (x:'T when 'T : (static member op_Explicit: 'T -> float) ) =
   float x

为什么会出现错误:“声明的类型参数 'T 不能在此处使用,因为类型参数无法在编译时解析”

在这个例子中,我提供了一个通用参数并限制它能够显式地转换为浮点数,并且所有的函数都被转换为浮点数,那么问题是什么?我已经阅读了所有与 F# 中的泛型相关的 MSDN 文档,但它们似乎只是绕圈子,与我在 Visual Studio 中看到的行为不符。据我了解,使用单引号语法'T适用于运行时泛型,而不是编译时泛型。

这让我想到了另一个问题。我经常看到有'T^T没有inline. 这与有关这些语法定义的 MSDN 文档背道而驰。我错过了什么吗?

此外,从文档来看,似乎应该能够自动推断出op_Explicit对类型的约束,而无需任何类型注释:'T

let func x =
   float x

但在这种情况下x推断出的类型是。int

4

2 回答 2

4

Here's a quickie-summary that may help out.

You use inline and ^T and member constraints to author weird code 'for all types T that have this ad-hoc API set'; this is code that cannot be authored directly in .NET (e.g. you can't write it in C#), and it must be inline because the F# compiler can inline/hard-code the specific type at each individual call site. This is a very advanced feature, and so you're unlikely to find too many docs/samples about it (and the error diagnostics are not always great).

You use 'T for normal generics, e.g. the usual generic stuff you do in C#. This is a mainline scenario.

Note that in both cases, it is often possible(/better/easier) to let F# infer types and genericity for you, rather than spelling it out. E.g.

let inline f x = float x

and the hover-tip in Visual Studio over f shows that the appropriate constraint has been inferred.

于 2012-06-08T20:19:15.557 回答
0

感谢@ildjarn,我找到了答案:

来自http://msdn.microsoft.com/en-us/library/dd548046

静态解析的类型参数主要与成员约束结合使用,成员约束是允许您指定类型参数必须具有特定成员或成员才能使用的约束。没有办法通过使用常规泛型类型参数来创建这种约束。

似乎 Visual Studio 应该给出一个不同的错误,然后,例如:“成员约束不能在此处使用,因为 'T 不是静态解析的类型”或“成员约束只能与静态解析的类型参数一起使用。 "

于 2012-06-08T20:08:55.773 回答