Я пытаюсь написать 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;
}
Кто-нибудь имеет представление о том, как написать только один шаблонный метод, который может обрабатывать как подписанные, так и неподписанные типы (может быть, как float, так и double)?Этот код должен поддерживать c ++ 03.
Спасибо.