Reputation: 4928
Let's say I have a templated object pool class as defined below:
template<class T, size_t pool_size>
class Pool
{
public:
create(int index, *init parameters*)
{
pool_objects_[index].init(*init parameters*);
};
private:
std::array<T, pool_size> pool_objects_;
}
This object pool class essentially creates a set number of objects, and then allows others to "create" object instances within the pool.
The trouble I'm running into is the create method. The arguments to this method are dependent on the actual Pool Object type. Thus I cannot declare a function that will work for every Pool object type.
For example, let's say I have two PoolObject types as defined below:
class Entity1;
class Entity2;
Each class instance requires a different set of parameters to initialize the object. Thus for my generic Pool class, I need the create method to accept different parameters depending on the Pool Object type.
What would be a good method for achieving this?
I assume I could create another template parameter which would let a user define an "InitObject". The init object would essentially be a struct that contains initialization information. This is outlined below:
template<class T, class T_init, size_t pool_size>
class Pool
{
public:
create(int index, T_init init_obj)
{
pool_objects_[index].init(init_obj);
};
private:
std::array<T, pool_size> pool_objects_;
}
Does this seem like a reasonable approach? Or does it seem like a template hack? I feel like T_init shouldn't have to be specified since we're already specify T, however, I'm not sure of an alternative.
Upvotes: 2
Views: 429
Reputation: 172964
You can make create
a variadic template, which takes a template parameter pack as template parameter. e.g.
template <typename... U>
void create(int index, U&&... u)
{
pool_objects_[index].init(std::forward<U>(u)...);
};
Then you could pass all the arguments for initializing (after index
) to create
, they'll be forwarded to init
later.
Upvotes: 4