假设我有以下数据结构:
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;
};
我想创建一个单个 工厂方法,它返回一个派生类的 vector ,其中 id、名称和类别在函数中是已知的。我遇到的问题是切片...
std::vector< Base* > getVector(...)
struct A 的数据成员丢失了! (dynamic_cast 回到生产代码中可接受的 A?)
所以我有了这个模板方法,但我仍然认为它不是最好的解决方案:
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;
}
有没有比模板法更好的方案呢?
最佳答案
您的要求似乎有问题,因为您想要:
- 抽象对象创建直到运行时
- 在编译时创建对象后访问特定成员
所以没有办法让它正常工作。您的模板代码仍然需要在调用方静态地知道您的对象的类型,因此对象的创建不会被抽象掉。
我的建议是重新思考你的问题:你为什么要有一个动态工厂?为什么不能所有对象都共享 Base
类中的访问器?
如果你不能清楚地回答这两个问题,这可能意味着你一开始就不应该有这个类层次结构。
关于C++ 对象工厂函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14946598/