我想创建一个Container类,我可以通过使用该对象成员变量作为其标识符从容器中检索对象。 但我得到一个编译错误,因为我想存储指针(?)/参照对象的成员变量存储对一个不同类的对象成员变量的引用
template <typename Object>
class Container
{
private:
template <typename dataType>
dataType Object::* memberVariable; // error here "data member 'memberVariable' cannot be a member template"
template <typename dataType>
std::map <dataType, Object*> instanceVarMap; // what would be more efficient; a Map or unordered_map? I heard that
std::map <unsigned int, Object*> instanceIntMap; // ...unordered_maps use more memory & Maps are better when integers are the keys
public;
template <typename dataType>
Collection(dataType Object::*nMemberVariable)
{
memberVariable = nMemberVariable;
}
template <typename dataType>
Object* operator[] (dataType nParam)
{
// do I need to check whether the element already exists or does
// stl already do this for me?
if (instanceVarMap.find(nParam) == instanceVarMap.end())
{
return NULL;
}
return instanceVarMap[ nParam ];
}
Object* operator[] (unsigned int nParam)
{
if (instanceIntMap.find(nParam) == instanceIntMap.end())
{
return NULL;
}
return instanceIntMap[ nParam ];
}
void store(Object* o)
{
if (o==NULL || instanceMap.contains(o->memeberVariable) != instanceMap.end()) { return; }
instanceIntMap.insert(o->ID, o);
instanceVarMap.insert(o->memberVariable, o); // is this the correct way I get the objects member variable? o->memberVariable
}
};
// I am doing this so I can use the class like so
struct FoodItem
{
unsigned int ID;
string name;
double price;
};
Collection <FoodItem*> foodCol(&FoodItem::name);
// after storing some FoodItems in foodCol, I can retreive a FoodItem either
// by their ID or their name
FoodItem* f = foodCol["coffee"]; // find FoodItem by their member variable 'name'
FoodItem* g = foodCol[1]; // find FoodItem by their ID var
这是什么:'集合 foodCol(&FoodItem :: name);'应该是什么意思?什么地址? –
2011-05-14 06:06:02
我想你的意思是&FoodItem :: name是什么意思,我指的是结构FoodItem的成员变量名称。因此,我创建了一个Collection并且我希望能够通过使用它们的名称作为关键字(标识符)来访问它的FoodItem元素 – user593747 2011-05-14 06:09:19