我有以下函数将字符串转换为数字数据类型:
template <typename T>
bool ConvertString(const std::string& theString, T& theResult)
{
std::istringstream iss(theString);
return !(iss >> theResult).fail();
}
Run Code Online (Sandbox Code Playgroud)
但这不适用于枚举类型,所以我做了类似这样的事情:
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;
}
Run Code Online (Sandbox Code Playgroud)
(我假设theString具有枚举类型的有效值;我主要用于简单序列化)
有没有办法创建一个结合这两者的单一功能?
我已经使用了模板参数,但没有提出任何建议; 如果不必为枚举类型调用一个函数而为其他所有函数调用另一个函数,那就太好了.
谢谢