相关疑难解决方法(0)

如何扩展词法转换以支持枚举类型?

我有以下函数将字符串转换为数字数据类型:

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具有枚举类型的有效值;我主要用于简单序列化)

有没有办法创建一个结合这两者的单一功能?

我已经使用了模板参数,但没有提出任何建议; 如果不必为枚举类型调用一个函数而为其他所有函数调用另一个函数,那就太好了.

谢谢

c++ enums serialization casting lexical-cast

22
推荐指数
2
解决办法
1万
查看次数

标签 统计

c++ ×1

casting ×1

enums ×1

lexical-cast ×1

serialization ×1