Recent

Author Topic: [Solved] How to overload Implicit / Explicit ?  (Read 2867 times)

v.denis

  • Guest
[Solved] How to overload Implicit / Explicit ?
« on: May 28, 2013, 08:36:39 am »
Hi,

How to overload Implicit / Explicit operators in FPC?

Thanks.
« Last Edit: May 28, 2013, 09:07:41 am by v.denis »

Leledumbo

  • Hero Member
  • *****
  • Posts: 8783
  • Programming + Glam Metal + Tae Kwon Do = Me
Re: How to overload Implicit / Explicit ?
« Reply #1 on: May 28, 2013, 08:41:16 am »
Try the same way as Delphi with {$mode delphi}? I don't know the current state, just try with latest trunk.

v.denis

  • Guest
Re: How to overload Implicit / Explicit ?
« Reply #2 on: May 28, 2013, 08:52:48 am »
such example

Code: [Select]
program ovl_delphi;

{$ifdef fpc}
{$mode delphi}
{$endif}


type
  TMyClass = record
    FName: string;
    constructor Create(const AName: string);
    class operator Implicit(const AValue: string): TMyClass;
  end;

  { TMyClass }

constructor TMyClass.Create(const AName: string);
begin
  FName := AName;
end;

class operator TMyClass.Implicit(const AValue: string): TMyClass;
begin
  Result := TMyClass.Create(AValue);
end;

var
  c: TMyClass;

begin
  c := 'hello';

end.

works fine both in FPC and Delphi,

but I need to implicitly create class (actually interface), not record. Delphi can't do that (well it can I guess in XE4 compiler based on LLVM)
« Last Edit: May 28, 2013, 09:00:41 am by v.denis »

v.denis

  • Guest
Re: How to overload Implicit / Explicit ?
« Reply #3 on: May 28, 2013, 09:02:29 am »
Solved.

It's even simpler than Delphi.

here's the declaration example

Code: [Select]
operator :=(const AValue: string): IMyIntf;
begin
  Result := TMyClass.Create(AValue);
end;

it can be used both as assignment to variable and as function argument
« Last Edit: May 28, 2013, 09:29:20 am by v.denis »

 

TinyPortal © 2005-2018