The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,860 other subscribers

As Delphi generics are not supported for free functions, wrap them in a record container.

Posted by jpluimers on 2018/01/31

Of the things not possible with generics in Delphi, I already wrote about Impossible: Property using Generics in Delphi.

Now it’s time to write about simulating a free function with generics as this is impossible:

function CreateManaged<T>(const value: T): IManaged<T>;

Usually I create a static record method for these, as records do not have VMT overhead, less RTTI overhead and I’ve been used to see records as helpers for other types long before helpers initially were introduced in Delphi 8 to extend classes..

Spring4D has an excellent example of such a record workaround in the Managed.New<T> commit:

type
  Managed = record
  public
    class function New<T>(const value: T): IManaged<T>; static;
  end;

...

class function Managed.New<T>(const value: T): IManaged<T>;
begin
  Result := TManaged<T>.Create(value);
end;

It basically is a factory for classes implementing the IManaged interface.

In the mean time, Managed has been renamed to Shared but the above code shows my point.

–jeroen

Reference: [WayBackClass Helpers documented in Delphi 2007, introduced in Delphi 8

5 Responses to “As Delphi generics are not supported for free functions, wrap them in a record container.”

  1. rvelthuis's avatar

    rvelthuis said

    FWIW, class static methods do not have an overhead either. OK, the class has, but not the static methods. No Self is passed.

  2. It is what I do too, but I think I already remarked that that would be one of my wishes for new Delphi features: standalone generic functions.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.