Array size

L

Luc Claustres

Is it possible to retrieve the number
of elements in a template array
dynamically allocated ?

void allocate()
{
int size = ...
T *pointer = new T[size];
}

void compute(T *pointer)
{
// Here I need the size but I can only access the pointer
}

Thanks.
 
D

David Harmon

On Sun, 5 Dec 2004 22:06:35 +0100 in comp.lang.c++, "Luc Claustres"
Is it possible to retrieve the number
of elements in a template array
dynamically allocated ?

void allocate()
{
int size = ...
T *pointer = new T[size];
}

void compute(T *pointer)
{
// Here I need the size but I can only access the pointer
}

Use std::vector, then use the vector's size() member function to get
the size. Avoid roll-your-own substitutes for standard library
classes.
 
B

Buster

Luc said:
Is it possible to retrieve the number
of elements in a template array
dynamically allocated ?

In general no. Store the size too if you're going to need it.
void allocate()
{
int size = ...
T *pointer = new T[size];

Memory leak.
}

void compute(T *pointer)
{
// Here I need the size but I can only access the pointer

In fact you can't access either.
 
V

Virtual

Not really, but you could add another template parameter that comes
before anything that's deduced by the compiler. I've assumed function
templates for simplicity.

template<class T>
void allocate()
{
int size = T *pointer = new T[size];
compute<size>(T);
}

template<int U, class T>
void compute(T *pointer)
{
//do whatever you want here
}

Hope that helps.
 
D

David Harmon

On 6 Dec 2004 02:43:34 -0800 in comp.lang.c++, "Virtual"
template<class T>
void allocate()
{
int size = T *pointer = new T[size];
Bogus.

compute<size>(T);

Also bogus, using a variable size for a template parameter.
 

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

Members online

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,476
Latest member
blackwatermelon

Latest Threads

Top