Templates lots of newbie qs.
Chris Warwick
sp at m.me.not
Thu Mar 8 07:07:36 PST 2007
Ok, never used templates before but i think i have the basic idea. Just have
a few questions and would welcome any corrections / sugestions on way's to
improve this, my first template.. (surprisingly had very little trouble
writing this and it compiling, not sure about working tho')
class vector(T)
{
// fitems will be intialized to default right? So no need for a default
constructor?
T[] fitems;
this(T[] source)
{
fitems = source.dup;
}
// Am i right in thinking that vector!(int) is a distinct type from T[],
so how do you pass
// a template instance of the same time to the constructor? Somthing
like this???
// compiles but im not sure if its right..
this(vector!(T) source)
{
fitems = source.fitems.dup;
}
void append(T item)
{
fitems ~= item;
}
bool remove(T item) // returns true if item removed
{
int i = indexOf(item);
if (i >= 0)
{
fitems[i..fitems.length-1] = fitems[i+1..fitems.length];
fitems.length = fitems.length-1;
return true;
}
else
{
return false;
}
}
int indexOf(T item) // returns -1 if not found
{
for (int i = 0; i < fitems.length; i++)
{
if (fitems[i] == item) { return i; }
}
return -1;
}
int length()
{
return fitems.length;
}
// Do i have the opIndex / opIndexAssign correct?
// Is there anyway to localy control whether bounds checking is on, so i
can turn it
// on or off for just this module?
T opIndex(int i)
{
return fitems[i];
}
void opIndexAssign(T item, int index)
{
fitems[index] = item;
}
}
And are class templates value types or referances types?
How well optimized is stuff like this? Will the opIndex/Assign optimize down
to similar speed as using a basic array?
For basic array stuff like this would it be better to use the "Functions as
Array Properties" feature? Can that be templatized? Can you writed a generic
function that takes an array as the first param.. Somthing like this...
template ArrayProps(T)
{
int indexOf(T[] arr, T item)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == item) { return i; }
}
return -1;
}
}
ArrayPros(int);
int[] foo = [0,1,2,3,4];
int ibetthisdontwork = foo.indexOf(3);
many thanks,
chris
More information about the Digitalmars-d-learn
mailing list