3

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.

12
  • 1
    You could declare Type PT = ^T; inside the record and use it as var m: TMiniStack<Integer>.PT; with m := TMiniStack<Integer>.Create;. Commented Aug 28, 2014 at 11:19
  • No it's not, because that question does A: not provide the answer and B: I already know how to make a pointer to operate within the generic type itself. I'm asking a specific followup question to the one you're referring to. Commented Aug 28, 2014 at 11:20
  • @LURD, I'm not interested in a ^T, I want a ^TMiniStack<T>. Commented Aug 28, 2014 at 11:21
  • Sorry, I should have read more thoroughly. Commented Aug 28, 2014 at 11:22
  • 1
    It does provide an answer as Barry clearly explains that it's not possible to declare a pointer to a generic type. Commented Aug 28, 2014 at 11:24

1 Answer 1

4

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.....

Sign up to request clarification or add additional context in comments.

3 Comments

It compiles (after adding an Integer to the record and adding an implementation for NewRec and correcting the syntax error - <T> should be after the name, not after class).
I would have posted a similar solution. The only disadvantage is that you have to address this type as TMyStaticClass<SomeType>.PRec instead of a simple PRec. I guess one can create an alias, once SomeType is known.
@rudy I think that is unavoidable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.