【发布时间】: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