Help with template


A

a

I'm having problem compiling this simple template program, my g++
complains it doesn't know what size and ia are on ArrayRC.

TIA,

John



#include <iostream.h>
#include <assert.h>

const int ARRAY_SIZE = 12;

template <class T>
class Array
{
protected:
int size;
T *ia;

public:
Array(int sz = ARRAY_SIZE)
{
size = sz;
ia = new T[size];
}

virtual ~Array()
{
delete [] ia;
}

int getSize()
{
return size;
}

virtual T& operator[] (int index)
{
return ia[index];
}
};

template <class T>
class ArrayRC : public Array<T>
{
public:
ArrayRC(int sz = ARRAY_SIZE) : Array<T>(sz)
{
}

T& operator[] (int index)
{
assert(index >= 0 && index < size);
return ia[index];
}
};


main()
{
Array<int> stuff;
Array<double> stuff2;

}
 
Ad

Advertisements

J

Jens Theisen

I'm having problem compiling this simple template program, my g++
complains it doesn't know what size and ia are on ArrayRC.

These names are referenced within a template and depend on a template
parameter. In that case, they need to be qualified. The following will work:

class ArrayRC : public Array<T>
{
public:
ArrayRC(int sz = ARRAY_SIZE) : Array<T>(sz)
{
}

T& operator[] (int index)
{
assert(index >= 0 && index < this->size);
return this->ia[index];
}
};

The background to this weird requirement is that is aids parsing.
Without the qualification, there are situations were the parser is lost
in deciding whether or not a name denotes an object (or function or
variable), or a type (or struct/class), or a template.

There are other cases like this:

template< typename T >
struct foo
{
typedef typename T::some_type some_type_t;
typedef typename T::template nested_template< int > some_other_t;
};

Both the "typename" and the "template" are necessary if, and allowed
only if, the specified type or template depends on a template parameter
(T in this case). This dependency can be indirect, as in you case, where
the base class depends on the only template parameter, or direct, as in
my example.

A wonderful book about this stuff is "C++ Templates" from Vandervoorde
and Josuttis (probably mispelled).

Jens
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top