【发布时间】:2023-03-31 05:58:01
【问题描述】:
我想在地图中存储多种类型的对象,我想出了这个解决方案。我必须知道每个对象的类型,所以我不能使用 boost::any。有没有更好的方法来做到这一点,或者这是一个可以接受的解决方案?
enum eType
{
TYPE_STRING,
TYPE_NUMBER,
};
class CType
{
public:
int GetType() { return m_Type; }
protected:
int m_Type;
};
template <typename T>
class CData : public CType
{
public:
CData(const T & rData, int iType)
{
m_Type = iType;
m_Data = rData;
}
T & GetData() { return m_Data; }
private:
T m_Data;
};
std::map<unsigned long, CType *> map_Data;
void main()
{
// Create a new data with TYPE_NUMBER
CData<short> data(32767, TYPE_NUMBER);
// Add it to the map
map_Data[0] = &data;
// Get the type
switch (map_Data[0]->GetType())
{
case TYPE_NUMBER:
{
// Cast the first element to CData
CData<short> * pField = (CData<short> *)map_Data[0];
// Print the data
printf("Data: %d\n", pField->GetData());
}
break;
case TYPE_STRING:
{
// Cast the first element to CData
CData<std::string> * pField = (CData<std::string> *)map_Data[0];
// Print the data
printf("Data: %s\n", pField->GetData().c_str());
}
break;
}
}
【问题讨论】:
-
你试过运行它吗?
void main也不存在 -
当然我试过了,它在visual studio中工作。
-
您是在征求意见。如果你运行它,编译器就会接受它。够好吗?
标签: c++ templates stl containers std