Skip to content

Instantly share code, notes, and snippets.

@Zoxc
Created March 13, 2013 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zoxc/5153662 to your computer and use it in GitHub Desktop.
Save Zoxc/5153662 to your computer and use it in GitHub Desktop.
Named constructors with new and delete as functions
# class is Scala or Haskell like traits or type classes
class Constructor[*Args] # Args is variadic
{
type Constructed
static construct(obj: *Constructed, args: Args): unit
}
class Destructable # All types have instance of this
{
destruct(): unit
}
struct A
{
field: int
inline: Struct
constructor : field(1) {} # A Constructor type class instance for A is created
constructor named(i) : field(i) {} # named is a dummy type that constructs A instances, a Constructor type class instance for it is created where the Constructed type is A
}
new[T: Constructor[Args], *Args](args: Args): *R
where R = T.Constructed
{
obj := C.malloc(sizeof R) as *R
T.construct(obj, args)
return obj
}
delete[T: Destructable](obj: *T)
{
(*obj).destruct()
C.free(obj)
}
lvar: A
var: := new[A]()
delete(var)
lvar: A.named(2)
var := new[A.named](2)
delete(var)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment