Page 1 of 1

Some kind of generics

Posted: Sat Sep 05, 2009 12:20 pm
by milan1612
I thought about how some kind of generic type system could be integrated into Purebasic
and this is what I came up with.

Code: Select all

Procedure AllocateStruct(Type struct)
  Protected *Ptr.struct = AllocateMemory(SizeOf(struct))
  ProcedureReturn Mem
EndProcedure
I know, this is a very bad example but I hope you get the idea. Similar to lists or maps
a type (= Structure) could be passed to a procedure which then could work with it
as if it was a variable. The SizeOf call is just an example, maybe one of you can
come up with something more suggestive.

The practical reason why I thought about generics is, I'm currently implementing
a custom data container which should work with all kind of datatypes. Of course
I could simply specify the size of the type as an argument, but this is kind of inelegant.

What do you think about this? Are there any pitfalls or problems I didn't take in account?

Posted: Sat Sep 05, 2009 12:53 pm
by Trond
Look at what I did here: http://www.purebasic.fr/english/viewtop ... selisttype

The actual code doesn't work any more, but it showcases the idea.

Posted: Sat Sep 05, 2009 1:17 pm
by milan1612
Yes, Macros are one way to achieve this, but they are more like C++ templates.
That is they 'generate' specialised instances of the functions. Negative side effects
are increased code size and sometimes hard to spot bugs.

Posted: Sun Sep 06, 2009 1:10 am
by Mistrel
Macros do not do type checking on non-generic parameters, have no address, cannot return a value, etc. They are not like C++ templates.

Posted: Sun Sep 06, 2009 9:10 am
by Trond
Mistrel wrote:Macros do not do type checking on non-generic parameters, have no address, cannot return a value, etc. They are not like C++ templates.
You didn't read my link, did you?