我试图在c ++中创建GenericType,我可以传递给std :: map 但它是限制我必须得到每种类型的通用类型的getter 支持这可能是复杂的类型将增长。 有没有办法让它更好,如果它可以没有模板或提升,但可以支持c ++ 11。
例如: //这是我需要使其更通用的GenericType
enum types {
INT_TYPE,
STRING_TYPE,
CUSTOM_TYPE
}
struct GenericType {
GenericType(int i) {
intVal = i
m_Type = INT_TYPE;
}
GenericType(std::string s) {
stringVal = s
m_Type = STRING_TYPE;
}
GenericType(CustomType ct) {
customTypeVal = ct
m_Type = CUSTOM_TYPE;
}
CustomType getCustomType() { return customTypeVal; };
std::string getStringType() { return stringVal; };
int getIntType() { return intVal; };
types getType() { return m_Type; };
private:
types m_Type;
std::string stringVal;
int intVal;
CustomType customTypeVal;
};
//Init the map
std::map<std::string, GenericType> ContainerMap;
ContainerMap["String"] = new GenericType("Foo");
ContainerMap["Int"] = new GenericType(111);
ContainerMap["CustomType"] =new CustomType (customTypeObj);
//Somewhere in the app
CustomType* pCustomType = ctmymap.find("String")->second;
if(pCustomType->getType() == STRING_TYPE) {
//Do something with String
}
CustomType* pCustomType = ctmymap.find("Int")->second;
if(pCustomType->getType() == INT_TYPE) {
//Do something with int
}
感谢帮助者!