Template classes

Denis Koroskin 2korden at gmail.com
Tue Apr 14 14:27:18 PDT 2009


On Wed, 15 Apr 2009 01:01:28 +0400, Andrew Spott <andrew.spott at gmail.com> wrote:

> So, the attached is supposed to be a class that creates a vector of any  
> type (I would like it to only take numerical values (int, float, real,  
> double, etc), however, I am ok with it taking others (not that I see why  
> someone would use it that way).
>
> I tried to compile it with the following, but it won't compile.  I don't  
> really understand the errors I'm getting either.
>
> Can someone tell me what I'm doing wrong?  If you need more information,  
> let me know.
>
> -Andrew
>
> void testvector() {
> 	auto v = new Vector!(float)(3, 12.0);
> 	writefln(v.toString());
> 	int n = 0;
> 	
> 	while (n < n.size()) {
> 		v[n] = n;
> 	}
> 	
> 	writefln(v.toString());
>
> }

You've got quite a few errors in your code:

module vector;
private import std.string;

class Vector(T) {
private:
	T[] v;
//	int nn; // there is no need to store a size of array separately. It is available as v.length
	
public:
	this() {
	}

	this(int n) {
//		nn = n; // not needed
		v = T[n]; // wrong, should be: v = new T[n];
	}

	this(int n, T a) {
//		nn = n;
		v = T[n]; // same here (see above)
		while (n > 0) { // v[] = a; is faster and does the same as the loop below
			n--;
			v[n] = a;
		}
	}

	T opIndex(int n, int m) { // this won't work, because float is not an array
		return v[n][m];   // try this: T opIndex(int n) { return v[n]; }
	}

	opIndexAssign(T)(T a, int n, int m) { // no need for a template, also you forgot to write function return type
		v[n][m] = a;             // should be: void opIndexAssign(int n, T a) { v[n] = a; }
	}

	int size() {
		return nn; // should be: return v.length;
	}

	string toString() {
		string s = "[";
		int n = 0;
		while ( n < nn) {
			s ~= v[n] ~ ", ";
		}
		return s ~ "]";
	}

	~this() { // no need for this one
	}
}


void testvector() {
	auto v = new Vector!(float)(3, 12.0);
	writefln(v.toString());
	int n = 0;
	
	while (n < n.size()) { // infinite loop
		v[n] = n;
	}
	
	writefln(v.toString());
 
}

Also, try using foreach instead of while and for loops.

For example,

string toString() {
    if (v.length == 0) return "[]";
    string s = "[";
    foreach (k; v[0..$-1]) {
        s = std.string.format("%s, %s", s, k);
    }
    s = std.string.format("%s, %s]", s, v[$-1]);
}

void testvector() {
    // ...
    foreach (index, ref value; v) {
        value = index;
    }
    // ...
}

Hope that helps.



More information about the Digitalmars-d-learn mailing list