Pointer to generic record

点点圈 提交于 2019-12-11 12:56:49

问题


Note that this is not a duplicate of Pointer to generic type. It's a followup question.

I know it is possible to define a pointer to any generic type.
It just that Delphi makes it complicated. It was meant to be impossible, but due to a compiler bug the option slipped through.
This is what the linked question answers.

My question is:

How do I define a pointer to a generic record without encapsulating it in a surrounding class?

Example code:

TGenericRecord<T> = record
  Data: integer;
  Procedure SomeMethod; inline; <<<< inlining is vital here. 
end;

I want to get a type safe pointer to TGenericRecord.
I do not want to wrap the record in a surrounding class because in my experiments I've found that that disables the inlining.

How do I get a typesafe generic pointer to this record.

Use case

{class} function create(size: integer): PGenericRecord{<T>}

I want to be able to create records on the heap in addition to the stack.


回答1:


I think your best bet probably looks like this:

type 
  TMyStaticClass<T> = class
  public
    type
      TRec = record
        ....
      end;
      PRec = ^TRec;
  public
    class function NewRec: PRec; static;
  end;

I don't have a compiler handy to check whether or not this even compiles but I feel that it should.....



来源:https://stackoverflow.com/questions/25547128/pointer-to-generic-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!