blob: 305c55cbf912a2b348784cbedd79a9081d16864d (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
// methods on generic structs: each set of type arguments gets its own copy
struct pt { int x, y; };
struct table<K, V> {
int n; K* keys; V* vals;
fn init(int cap) {
this.n = 0;
this.keys = new(K, cap) as K*;
this.vals = new(V, cap) as V*;
return 0;
}
fn put(K k, V v) {
this.keys[this.n] = k;
this.vals[this.n] = v;
this.n++;
return this.n;
}
fn width() { return sizeof(K) * 10 + sizeof(V); }
fn total() {
int s = 0;
for (int i = 0; i < this.n; i++) s += this.vals[i];
return s;
}
};
int main() {
table<int, int> a;
a.init(8);
a.put(1, 10); a.put(2, 20); a.put(3, 30);
put_n(a.n); put_c(' '); put_n(a.total()); put_c(' '); put_n(a.width()); put_c(' ');
table<pt, int>* b = new(table<pt, int>);
b.init(4);
put_n(b.width()); put_c(' ');
table<int, pt>* c = new(table<int, pt>);
c.init(4);
put_n(c.width()); put_c(10);
return 0;
}
|