使用 GetTypeKind 时如何触发编译时错误
How to trigger a compile-time error when using GetTypeKind
在 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;
如果没有使用正确的类型,我希望编译器生成编译时错误。
这允许在较早阶段捕获任何错误。
这可能吗?
我的思路是这样的:
- 如果测试为假,则不会生成测试中的代码。
- 如果测试为真,则确实会生成代码。
是否有一些我可以放入测试中的代码会在生成代码时使编译器出错,但不会使解析器停止工作?
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 构造函数中放置一个断言。它看起来像这样:
class constructor TDetours<T>.CreateClass;
begin
Assert(Sizeof(T) = Sizeof(Pointer));
Assert(GetTypeKind(T) = tkProcedure);
end;
在 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;
如果没有使用正确的类型,我希望编译器生成编译时错误。
这允许在较早阶段捕获任何错误。
这可能吗?
我的思路是这样的:
- 如果测试为假,则不会生成测试中的代码。
- 如果测试为真,则确实会生成代码。
是否有一些我可以放入测试中的代码会在生成代码时使编译器出错,但不会使解析器停止工作?
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 构造函数中放置一个断言。它看起来像这样:
class constructor TDetours<T>.CreateClass;
begin
Assert(Sizeof(T) = Sizeof(Pointer));
Assert(GetTypeKind(T) = tkProcedure);
end;