ean*_*ang 4 c++ oop collections typeid
我有以下类使用3个不同的映射:键总是字符串,而值可以是字符串,整数或浮点数.
class MyMaps
{
public:
template<typename T> void addKey(const std::string& key);
void addValue(const std::string& key, const std::string& value);
void addValue(const std::string& key, int value);
void addValue(const std::string& key, float value);
private:
std::map<std::string, std::string> stringFields;
std::map<std::string, int> intFields;
std::map<std::string, float> floatFields;
};
Run Code Online (Sandbox Code Playgroud)
这些addValue()函数只是将新对添加到相关地图中.我正在做的是addKey()模板功能:
/** Add only a key, the related value is a default one and is specified by template parameter T. */
template<typename T>
void MyMaps::addKey(const string& key)
{
if (typeid(T) == typeid(string))
{
stringFields.insert(pair<string, string>(key, string()));
}
else if (typeid(T) == typeid(int))
{
intFields.insert(pair<string, int>(key, int()));;
}
else if (typeid(T) == typeid(float))
{
floatFields.insert(pair<string, float>(key, float()));
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,我正在使用template,typeid()因为我不喜欢这种依赖于type-in-function-name的替代方法:
void MyMaps::addStringKey(const string& key)
{
stringFields.insert(pair<string, string>(key, string()));
}
void MyMaps::addIntKey(const string& key)
{
intFields.insert(pair<string, int>(key, int()));
}
void MyMaps::addFloatKey(const string& key)
{
floatFields.insert(pair<string, float>(key, float()));
}
Run Code Online (Sandbox Code Playgroud)
第一个addKey()版本似乎有效,但我想知道是否有更优雅的解决方案.也许我错过了一些面向对象的设计概念,在这种情况下可能会有所帮助?
提前致谢.
这非常适合模板专业化:
template<>
void MyMaps::addKey<string>(const string& key)
{
stringFields.insert(pair<string, string>(key, string()));
}
template<>
void MyMaps::addKey<int>(const int& key)
{
intFields.insert(pair<string, int>(key, int()));;
}
template<>
void MyMaps::addKey<float>(const float& key)
{
floatFields.insert(pair<string, float>(key, float()));
}
Run Code Online (Sandbox Code Playgroud)
编辑:有关模板专业化的语法/更多信息,请阅读:模板专业化和部分模板专业化
或者更好的是,如果提升是一个选项,并且如果所有3个地图的键都是唯一的,并且您有3个不同的地图只是为了能够存储它们,那么请考虑使用boost::variant:
typedef boost::variant<string, int, float> ValueType;
class MyMap
{
public:
typedef std::map<std::string, ValueType> MapType;
template<typename T> void addKey(const std::string& key, T &val)
{
ValueType varVal= val;
allFields.insert(MapType::value_type(key, varVal));
}
private:
MapType allFields;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
804 次 |
| 最近记录: |