我正在尝试编写一个xml流媒体,如果可以完成转换,该流媒体将返回元素属性的特定类型。 我编写了getString方法以将属性作为字符串获取,然后尝试将字符串转换为用户请求的特定类型,如下所示:
bool CXmlStreamer::getShort(const std::string & elementPath, const std::string & attribute, short & output)
{
return getSignedValue<short>(elementPath, attribute, output);
}
bool CXmlStreamer::getUShort(const std::string & elementPath, const std::string & attribute, unsigned short & output)
{
return getUnsignedValue<unsigned short>(elementPath, attribute, output);
}
为了处理有符号/无符号类型,我创建了2种方法,如下所示:
template<typename T>
inline bool CXmlStreamer::getSignedValue(const std::string & elementPath, const std::string & attribute, T & output)
{
bool isSuccess = false;
std::string str;
bool isStrSuccess = getString(elementPath, attribute, str);
if (isStrSuccess)
{
// Converting to long
// if the convert is success, check valid range of the template type
char *endPtr;
long convertedAsLong = strtol(str.c_str(), &endPtr, 10);
if ((str.at(0) != '\0') &&
(*endPtr == '\0') &&
(convertedAsLong <= std::numeric_limits<T>::max()) &&
(convertedAsLong >= std::numeric_limits<T>::min()))
{
isSuccess = true;
output = (T)convertedAsLong;
}
}
return isSuccess;
}
template<typename T>
inline bool CXmlStreamer::getUnsignedValue(const std::string & elementPath, const std::string & attribute, T & output)
{
bool isSuccess = false;
std::string str;
bool isStrSuccess = getString(elementPath, attribute, str);
if (isStrSuccess)
{
// Converting to unsigned long
// if the convert is success, check valid range of the template type
char *endPtr;
unsigned long convertedAsULong = strtoul(str.c_str(), &endPtr, 10);
if ((str.at(0) != '\0') &&
(str.at(0) != '-') &&
(*endPtr == '\0') &&
(convertedAsULong <= std::numeric_limits<T>::max()))
{
isSuccess = true;
output = (T)convertedAsULong;
}
}
return isSuccess;
}
有人对如何只编写一种可同时处理有符号和无符号类型(可能还有浮点和双精度)的模板方法有任何想法吗? 该代码必须支持c ++ 03。
谢谢。