Created
March 13, 2013 16:13
-
-
Save Zoxc/5153662 to your computer and use it in GitHub Desktop.
Named constructors with new and delete as functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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