【发布时间】:2010-12-04 10:38:35
【问题描述】:
我有以下函数可以将字符串转换为数字数据类型:
template <typename T>
bool ConvertString(const std::string& theString, T& theResult)
{
std::istringstream iss(theString);
return !(iss >> theResult).fail();
}
但是,这不适用于枚举类型,所以我做了这样的事情:
template <typename T>
bool ConvertStringToEnum(const std::string& theString, T& theResult)
{
std::istringstream iss(theString);
unsigned int temp;
const bool isValid = !(iss >> temp).fail();
theResult = static_cast<T>(temp);
return isValid;
}
(我假设 theString 对枚举类型具有有效值;我主要将其用于简单的序列化)
有没有办法创建一个结合了这两者的单一功能?
我对模板参数进行了一些尝试,但没有提出任何建议;不必为枚举类型调用一个函数而为其他所有类型调用另一个函数,这真是太好了。
谢谢
【问题讨论】:
标签: c++ serialization enums casting lexical-cast