Templates
Lorenzo Villani
arbiter at arbiterlab.net
Tue Jan 15 09:19:01 PST 2008
Hi, i have a little problem with a simple class (please note that I'm a D newbie)
The folllowing is an initial implementation of a Vector class using templates, modeled after Qt's QVector. As you might notice this is a class wrapper around dynamic sized arrays.
(there's only a little part of the code implemented)
module std.Vector;
class Vector(T) {
private:
T[] a;
public:
this() {}
void append(T value) {
a.length = a.length + 1;
a[a.length - 1] = value;
}
T at(int i) {
assert(i >= 0 && i < a.length);
return a[i];
}
int capacity() {
return size();
}
void clear() {
a.length = 0;
}
bool contains(/*const*/ T value) {
bool c = false;
foreach (element; a) {
if (element == T) {
c = true;
break;
}
}
return c;
}
int count(/*const*/ T value) {
int c = 0;
foreach (element; a) {
if (element == T)
c++;
}
return c;
}
int count() {
return size();
}
T first() {
return a[0];
}
int indexOf(/*const*/ T value, int from = 0) {
int ret = -1;
for (int i = from; i < a.length; i++) {
if (a[i] == value)
ret = i;
}
return ret;
}
bool isEmpty() {
if (a.length > 0)
return true;
else
return false;
}
T last() {
return a[a.length];
}
void popBack() {}
void popFront() {}
void prepend(/*const*/ T value) {}
void pushBack(/*const*/ T value) {}
void pushFront(/*const*/ T value) {}
void remove(int i) {
}
void remove(int i, int count) {
}
void replace(int i, /*const*/ T value) {}
void resize(int size) {
a.length = size;
}
int size() {
return a.length;
}
T value(int i) {
assert(i >= 0);
if (i > a.length) {
return T;
} else {
return a[i];
}
}
// TODO: Implement operators
}
Now, if I build a very simple test program such as
import std.stdio;
import std.Vector;
int main() {
Vector!(Object) myVec;
myvec.size();
return 0;
}
The application would compile fine but give a segfault when running. I'm running Linux with Digital Mars D Compiler v1.015 on a Fedora 8 box.
PS: Can you tell me why the compiler doesn't let me use consts in functions declarations?
PPS: I've noticed that the compiler sometimes doesn't tell me about evident mistakes such as writing assertiii() instead of assert() when using CMakeD to build the project...
More information about the Digitalmars-d
mailing list