gpt4 book ai didi

c++ - 存储对具有不同类的对象成员变量的引用

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:46:50 26 4
gpt4 key购买 nike

我正在尝试创建一个 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

最佳答案

在 C++ 中不允许声明模板数据成员(不要与定义静态成员时使用的模板语法混淆)。最好的实现方式是,

template <typename Object, typename dataType>  // <-- Add dataType here
class Container
{
private:
dataType Object::* memberVariable; // use 'dataType' simply
// ...
};

关于c++ - 存储对具有不同类的对象成员变量的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6000111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com