Default parameter value for a TSomething in Delphi
Asked Answered
C

4

7

I'd like to know if this is possible in Delphi (or if there's a clean way around it):

type
 TSomething = record
  X, Y : Integer;
 end;

GetSomething( x, y ) -> Returns record with those values.

... and then you have this function with TSomething as parameter, and you want to default it as

function Foo( Something : TSomething = GetSomething( 1, 3 );

The compiler spits an error here, however I'm not sure if there's a way around it!

Can this be done?

Captivate answered 20/9, 2010 at 10:55 Comment(0)
R
6

The easiest way is to use overloaded procedures:

program TestOverloading;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TSomething = record
    X,Y : integer;
  end;

const
  cDefaultSomething : TSomething = (X:100; Y:200);

procedure Foo(aSomething : TSomething); overload;
begin
  writeln('X:',aSomething.X);
  writeln('Y:',aSomething.Y);
end;

procedure Foo; overload;
begin
  Foo(cDefaultSomething);
end;

begin
  Foo;
  readln;
end.
Reconstructive answered 20/9, 2010 at 11:19 Comment(0)
T
12

Use overloading:

procedure Foo(const ASomething: TSomething); overload;
begin
  // do something with ASomething
end;

procedure Foo; overload;
begin
  Foo(GetSomething(1, 3));
end;
Tabu answered 20/9, 2010 at 11:3 Comment(0)
R
6

The easiest way is to use overloaded procedures:

program TestOverloading;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TSomething = record
    X,Y : integer;
  end;

const
  cDefaultSomething : TSomething = (X:100; Y:200);

procedure Foo(aSomething : TSomething); overload;
begin
  writeln('X:',aSomething.X);
  writeln('Y:',aSomething.Y);
end;

procedure Foo; overload;
begin
  Foo(cDefaultSomething);
end;

begin
  Foo;
  readln;
end.
Reconstructive answered 20/9, 2010 at 11:19 Comment(0)
T
3

Use a class instead of a record and something like this would do it:

TSomething = class
public 
  X: integer;
  Y: integer
end;

procedure Foo(Something: TSomething = nil);
begin
  if (Something = nil) then
    Something := GetSomething(1, 3);
  ...
end;
Trismus answered 20/9, 2010 at 10:59 Comment(2)
To exclude some RTTI overhead, X and Y could be declared as 'public' instead of implicit 'published'Exiguous
Thank you @mjustin for pointing this out. My implicit assumption was, that the directive to control the generation of RTTI is set to the default value: {$M-}. ;-)Trismus
C
2

If you use a pointer instead of the record type you can use nil as default value:

type
  TSomething = record
    X, Y : Integer;
  end;

  PSomething = ^TSomething;

function Foo(Something: PSomething = nil);

Actually, passing pointers as parameters is usually faster because it avoids copying blocks of memory.

Cruciform answered 21/5, 2013 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.