【问题标题】:C++ convert string to enum?C ++将字符串转换为枚举?
【发布时间】:2015-06-10 05:35:54
【问题描述】:

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

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 中,但我正在对此进行测试。

【问题讨论】:

  • 正如我所说,在 SO ... stackoverflow.com/questions/1528374/… 上找到了它,但无法让它工作,尽管对我来说似乎应该。
  • 如果不使用特定于编译器的特殊扩展(而且我认为任何主要编译器都没有任何此类功能)或使用从字符串到枚举值的映射,根本无法做到这一点。
  • 会不会是在示例帖子中他们扩展了 boost 词法转换?如果是这样,我正在使用 boost。
  • 还有一个 boost::enum 包可以做到这一点(虽然使用宏)

标签: templates c++11 boost enums


【解决方案1】:

您没有正确使用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

解决方案

为了支持您的使用,您需要执行其他人在 cmets 中建议的操作(例如,mapping of string representation to enum

【讨论】:

  • 加1努力。我只是链接到链接的答案:) 这是 OP 的闪亮答案
猜你喜欢
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 2010-09-06
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多