Recent

Author Topic: Generic function of non-generic class  (Read 760 times)

cch

  • Newbie
  • Posts: 6
Generic function of non-generic class
« on: September 30, 2020, 11:22:03 am »
Hi!
I want to have a generic function inside a non-generic class. Something like that
Code: Pascal  [Select][+][-]
  1. program project1;
  2. {$mode objfpc}
  3.  
  4. type
  5.     generic grec<T> = record
  6.         value: T;
  7.     end;
  8.  
  9.     tmytype = class
  10.     public
  11.     generic function func1<T>( const v: variant ): specialize grec<T>;
  12.     end;
  13.  
  14. var
  15.     tmp: tmytype;
  16.     vr: variant;
  17.     res: string;
  18.     gr: specialize grec<string>;
  19.  
  20. generic function tmytype.func1<T>( const v: variant ): specialize grec<T>;
  21. begin
  22.     result.value := t(v);
  23. end;
  24.  
  25. generic function func11<T>( const v: variant ): specialize grec<T>;
  26. begin
  27.     result.value := t(v);
  28. end;
  29.  
  30. begin
  31. vr := 123;
  32.  
  33. tmp := tmytype.Create;
  34. //with tmp do
  35. gr := specialize tmp.func1<string>( vr );
  36. writeln(gr.value);
  37. tmp.Free;
  38.  
  39. writeln(specialize func11<string>( vr ).value);
  40.  
  41. readln;
  42.  
  43. end .            
But it does not compile giving error
Quote
project1.lpr(35,21) Fatal: Syntax error, "<" expected but "." found
on line
Code: Pascal  [Select][+][-]
  1. gr := specialize tmp.func1<string>( vr );
The "with" clause does not work either with "project1.lpr(35,31) Error: Illegal expression"
Code: Pascal  [Select][+][-]
  1. with tmp do
  2. gr := specialize func1<string>( vr );
The func11 works fine after all.

Is it not supported or am I missing something?
Lazarus 2.0.10, fpc 3.2.0, x64

Thanks

PascalDragon

  • Hero Member
  • *****
  • Posts: 5462
  • Compiler Developer
Re: Generic function of non-generic class
« Reply #1 on: September 30, 2020, 01:41:43 pm »
But it does not compile giving error
Quote
project1.lpr(35,21) Fatal: Syntax error, "<" expected but "." found
on line
Code: Pascal  [Select][+][-]
  1. gr := specialize tmp.func1<string>( vr );

The specialize keyword is part of the generic you want to specialize - in this case the func1<> - thus you need to write:

Code: Pascal  [Select][+][-]
  1. gr := tmp.specialize func1<string>( vr );

The "with" clause does not work either with "project1.lpr(35,31) Error: Illegal expression"
Code: Pascal  [Select][+][-]
  1. with tmp do
  2. gr := specialize func1<string>( vr );

That would indeed be a bug. Would you please report it so that it isn't forgotten?

cch

  • Newbie
  • Posts: 6
Re: Generic function of non-generic class
« Reply #2 on: September 30, 2020, 02:05:09 pm »
Quote
gr := tmp.specialize func1<string>( vr );
wow, I would never think of it, thank you!
Quote
That would indeed be a bug. Would you please report it so that it isn't forgotten?
sure, here it is
https://bugs.freepascal.org/view.php?id=37844

 

TinyPortal © 2005-2018