从流到枚举类型的输入
如何从流输入到枚举类型?
我也能做到,
unsigned int sex = 0;
stream >> sex;
student.m_bio.sex = static_cast<Sex>(sex);
不然呢?
How to input from stream to enum type?
I can do it so
unsigned int sex = 0;
stream >> sex;
student.m_bio.sex = static_cast<Sex>(sex);
Otherwise?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你想确保该值有效,你可以这样做:
If you want to ensure that the value is valid, you can do something like this:
这个问题在这里以更一般的形式提出:如何以通用方式从 std::istream 读取枚举。
OP 几乎已经有了一个可行的解决方案;他只是在使用
const
时遇到了一些麻烦,以及一些不必要的尖括号。下面是充实的工作解决方案:read_enum
函数模板与标准中的std::make_pair
或std::make_shared
具有相同的用途库:它让我们省去了尖括号。您同样可以在 >> 中编写EnumReader(val.mSide)>> EnumReader(val.mType)
,但这更多的是打字(双关语)。据称,一些供应商的标准库在其
标头中仍然缺少std::underlying_type
。如果您有这些不完整的库之一,则可以使用 如何知道类枚举的底层类型?。This question was asked in a more general form over here: How to read enums from a std::istream in a generic fashion.
The OP almost had a working solution as it was; he just had some trouble with
const
, and a few unnecessary angle-brackets. Here's the working solution fleshed out:The
read_enum
function template serves the same purpose here asstd::make_pair
orstd::make_shared
in the standard library: it lets us dispense with the angle brackets. You could equally well writein >> EnumReader<enSide>(val.mSide) >> EnumReader<enType>(val.mType)
, but that's more typing (pun intended).A few vendors' standard libraries are allegedly still missing
std::underlying_type
from their<type_traits>
headers. If you have one of these incomplete libraries, you can use one of the workarounds listed at How to know underlying type of class enum?.这并不漂亮,但应该做到,
干杯,
CC
This is not pretty but should do it
Cheers,
CC