如何转换指针到通用参数类型? [英] Howto cast pointer to generic parameter type?

查看:144
本文介绍了如何转换指针到通用参数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个问题,很高兴找到这个网站。

it's my first question here, glad to have found this site.

我的问题涉及Delphi 2009的新的泛型特性。基本上我试图写一个泛型用于现有哈希映射实现的包装类。现有的实现存储(String,Pointer)对,因此在包装类中,我必须在通用参数类型T和指针类型之间转换。反之亦然。

My question deals with the new Generics feature in Delphi 2009. Basically I tried to write a generic wrapper class for an existing hash map implementation. The existing implementation stores (String, Pointer) pairs, so in the wrapper class I have to cast between the generic parameter type T and the Pointer type and vice versa.

type THashMap <T : class> = class
private
  FHashList   : THashList;
  ...

end;

我想到这样的一个类型(值:T)

I thought of a cast like this (Value : T)

Value := (TObject (Ptr)) as T

但这不工作。编译器告诉我'Operator不适用于这个操作数类型'。

But this doesn't work. The compiler tells me 'Operator not applicable to this operand type'.

有人有一些提示?非常感谢。

Somebody has some hints? Thanks a lot in advance.

推荐答案

您需要获取通用类型参数类型的位置的地址,然后类型转换地址到指向所需类型的指针,然后取消引用此指针并分配到结果位置。例如:

You need to take the address of the location of the generic type parameter type, then typecast this address to a pointer to the desired type, and then dereference this pointer and assign into the resulting location. For example:

PObject(@Value)^ := Ptr;

你不能只是类型转换类型T的值,其中T是不受约束的,编译器不知道T的大小;通常,非数字类型转换器只能将值转换为具有相同大小的类型。

The reason you can't just typecast a value of type T, where T is unconstrained, is that the compiler doesn't know the size of T; normally, non-numeric typecasts can only convert values into types that are of the same size.

不幸的是,编译器不够聪明,不能确定类类型约束意味着T保证与指针的大小相同。

Unfortunately, the compiler is not smart enough to figure out that a class-type constraint means that T is guaranteed to be the same size as a pointer.

此外,当前Delphi 2009泛型有一个问题,它创建了指向类型参数类型的指针。编译器不支持通用指针,但编译器允许在类中使用此语法:

Also, there is an issue with current Delphi 2009 generics with creating pointers to type parameter types. Generic pointers are not supported by the compiler, but the compiler permits this syntax inside classes:

type
  C<T> = class
  type
    PT = ^T; // UNSUPPORTED!
  end;

这可能适用于某些情况,可能对您的特定问题有帮助,事故和一般不支持。使用风险自负。

This may work for certain scenarios - and can be helpful for your specific problem - but it only works by accident and is not generally supported. Use at your own risk.

这篇关于如何转换指针到通用参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆