Lets say I have the following data structures:
struct Base
{
Base(const int id, const std::string &name, const std::string &category):
id(id), name(name), category(category) {}
int id;
std::string name;
std::string category;
};
struct A : public Base
{
A(const int id, const std::string &name, const std::string &category,
const int x, const int y) :
Base(id, name, category), x(x), y(y) {}
int x, y;
};
I want to create a single factory method that returns a vector of the derived classes, where the id, name, and category is known in the function. The problem that I run into is slicing...
std::vector< Base* > getVector(...)
Data members of struct A are lost! (dynamic_cast back to A acceptable in production code?)
So I have this template method, but I still don't think its the best solution:
template< class T >
std::vector< T > getVector()
{
std::vector< T > retVal;
retVal.push_back(T(45, "The Matrix", "Science Fiction"));
retVal.push_back(T(45, "Good Luck Chuck", "Comedy"));
...
return retVal;
}
Is there any better solution other than the template method?