I haven't had much experience with templates, but I wanted to make a memory pool class which can allocate any kind of object which is specified when the constructor is called, and allow them to be returned sequentially one at a time by a function call without again passing a template parameter. This was my first attempt but I realised it's impossible to do it this way as we don't know the type in getNext()
class MemoryPool{
template<typename T>
MemoryPool(int numObjects)
{
position = 0;
size = sizeof(T);
memory = new T[numObjects];
}
T* getNext()
{
position++;
returnstatic_cast<T*>(memory[position*size-size]);
}
private:
void* memory;
int size;
int position;
};
Is there any way of storing a type? I can't help feeling that my approach is all wrong either, I don't know how I got this far into C++ without ever really using templates...so if anyone has made a memory pool before and can suggest a better way of doing it that'd be great.
I have no idea what you are talking about. A constructor is only called once, so you have one template ergument per one instance of the class. That's just a regular template. Swap lines 1 and 2 and it should (almost) work.
Where you thinking about some sort of stack that could hold any kind of elements?
@ hamsterman: It sounds like he just wants it to hold one datatype. But "T" is created when the object is initiated so this should work right? I thought the OP wanted to use the new 'auto' so that they don't have to type as much?
Glad I could help. Now, here's some template-foo, in case you do want a type preserving stack. http://pastebin.com/kzD0TsD8
I guess that Nil is a bit unnecessary..
I just wanted to add that if you want to delay the T constructor calls,
you could reserve memory using malloc in your MemoryPool constructor
and then use placement new inside your getNext function (you could
provide several getNext overloads with varying number of arguments).