C++ 将字符串转换为枚举?

C++ convert string to enum?

我试图在 Linux 上将字符串转换为枚举类型。我在 Whosebug 上找到了这段代码来做这件事,但我不确定我是否正确使用了函数模板。它编译得很好。

template <typename T>
typename boost::enable_if< boost::is_enum<T>, bool>::type
convert_string(const std::string& theString, T& theResult)
{
    typedef typename std::underlying_type<T>::type safe_type;

    std::istringstream iss(theString);
    safe_type temp; 
    const bool isValid = !(iss >> temp).fail();
    theResult = static_cast<T>(temp);

    return isValid;
} 

这里我正在尝试正确使用它。

enum TestType {
    A1,
    B2,
    C3
};

string s = "A1";
TestType tt;

convert_string(s, tt);

问题是convert_string失败,调用后tt始终为0。此外,枚举位于中间件的 IDL 中,但我正在对此进行测试。

您没有正确使用 convert_string 函数。

typedef typename std::underlying_type::type safe_type;

这是确定枚举值的存储类型(例如,int、long long 等)。

然后这个类型用来把theString转换成temp,也就是数值类型。因此,istringstream 的工作原理是将 表示数值的字符串 (例如,“0”、“1”等)到一个数值。

鉴于此信息,您应该明白为什么您的代码不起作用,但以下代码却起作用。

代码

enum TestType
{
    A1,
    B2,
    C3
};

template<typename T>
typename std::enable_if<std::is_enum<T>::value, bool>::type
convert_string(const std::string& theString, T& theResult)
{
    typedef typename std::underlying_type<T>::type safe_type;

    std::istringstream iss(theString);
    safe_type temp; 
    const bool isValid = !(iss >> temp).fail();
    theResult = static_cast<T>(temp);

    return isValid;
}

int main()
{
    std::string s = "0"; // This is the value of A1
    TestType tt;

    std::cout << std::boolalpha << convert_string(s, tt) << "\n";
    std::cout << std::boolalpha << (A1 == tt) << "\n";

    return 0;
}

输出

true
true

解决方案

为了支持您的使用,您需要像其他人在评论中建议的那样做一些事情(例如,mapping of string representation to enum