您可以使用模板来做到这一点。
编辑:基于额外信息的新实现。如果mymap
是std::map<int, Shape*>
:
template <typename T>
void lookup(int idNum, T* &ptr) {
auto it = mymap.find(idNum);
if (it == mymap.end()) {
ptr = 0;
} else {
ptr = dynamic_cast<T*>(*it); // Shape must have a virtual member function
}
}
或者你可能更喜欢:
template <typename T>
T* lookup(int idNum) {
auto it = mymap.find(idNum);
if (it == mymap.end()) {
return 0;
}
return dynamic_cast<T*>(*it);
}
然后调用它像Circle *circle = database.lookup<Circle>(123);
显然多态性容器的乐趣本身就是一个一大堆,但我会假设你已经排序。那里可能有一个shared_ptr
,我已经遗漏了。
旧的实现时,我想到了DB可以存储POD的副本:
template <typename T>
void lookup(int idNum, T* &ptr) {
void *theresult = // something based on idNum
// some check needed here that theresult really is the right type.
// how you do this depends on the database, but suppose that
// the database gives us some integer "type" which indicates the type
if (type != type_constant<T>::value) {
ptr = 0;
} else {
ptr = static_cast<T*>(theresult);
}
}
type_constant是 “型特征” 的一个例子,你实现它想:
template <typename T>
struct type_constant {};
template <>
struct type_constant<Circle> {
static const int value = 1;
};
template <>
struct type_constant<Rectangle> {
static const int value = 2;
};
// etc...
IMO,这实际上是一个数据库问题。你也不会说什么数据库。我会查看SQL关键字“LIKE”。 – JustBoo 2010-08-19 15:49:36
你打算如何将类型信息传递给数据库? (或者我应该说,数据库将如何接收它?) – 2010-08-19 15:50:19
如果您希望数据库使用此信息*执行某些操作*,则必须编写一些特定于圆的代码,某些矩形特定的代码等等令人厌恶。问题是*你想把这个代码放在哪里。你能告诉我们你想要数据库做什么吗? – Beta 2010-08-19 15:51:50