delphi - 使用 GetTypeKind 时如何触发编译时错误

标签 delphi delphi-xe7 type-safety

在 XE7 中,我们有新的编译器内部函数 GetTypeKind(尚未记录),它允许我们在编译时提取类型的风格。

如果使用错误的类型,以下代码将生成运行时错误:

//make sure T is a procedure/function
procedure TDetours<T>.CheckTType;
{$IF CompilerVersion >= 28}
begin
  // XE7 and up:Resolve all tests at compiletime.
  if (Sizeof(T) <> Sizeof(Pointer)) or (GetTypeKind(T) <> tkProcedure) then begin
    raise DetourException.Create('T must be a procedure or function');
  end;
{$ELSE}
  //Code for pre-XE7 versions
{$ENDIF}
end;

如果未使用正确的类型,我希望编译器生成编译时错误
这允许在早期阶段捕获任何错误。 这可能吗?

我的思路是这样的:
- 如果测试为 false,则不会生成测试中的代码。
- 如果测试为真,则确实会生成代码。

是否有一些代码可以放入测试中,这些代码在生成代码时会使编译器出错,但不会使解析器停止工作?

最佳答案

In XE7 we have the new compiler intrinsic function GetTypeKind (as yet undocumented) that allows us to extract the flavor of a type at compile time.

为了能够做到这一点,您需要能够输入 GetTypeKind转化为条件表达式。这样你就可以编写这样的代码:

{$IF GetTypeKind(T) <> tkProcedure}
  {$Message Fatal 'Invalid type'}
{$ENDIF}

但是编译器不接受这个。编译器需要 $IF 中的表达式条件为常量表达式,并且 GetTypeKind(T) <> tkProcedure不是。

I want the compiler to generate a compile-time error if the correct type kind is not used. This allows be to catch any errors at an earlier stage. Is this possible?

这是不可能的。您唯一可用的机制是通用约束。并且通用约束没有足够的粒度来指定您需要的约束。

我认为最好的选择是在类构造函数中放置断言。它看起来像这样:

class constructor TDetours<T>.CreateClass;
begin
  Assert(Sizeof(T) = Sizeof(Pointer));
  Assert(GetTypeKind(T) = tkProcedure);
end;

关于delphi - 使用 GetTypeKind 时如何触发编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29518596/

相关文章:

delphi - 如何使用 TurboPower Lockbox 3.5 检测解密失败

delphi - 查询当前CPU的频率

delphi - 如何将 TObject 转换为 TObjectList<T>?

java - ArrayList 包含错误的类型对象,没有明确的原始类型转换

java - 包含原语的 Scala 集合的安全转换

delphi - JVCL 组件文档

delphi - 如果区域设置没有代码页,如何检测区域设置/语言?

delphi - 创建表单时不会调用 TPicture 属性的 Set 方法

delphi - 使用 THTTPRIO 时如何停止出现身份验证对话框

Java:使用反射正确检查类实例化