将枚举值转换为整数时如何避免编译器警告?
我创建了一个类 CMyClass
,其 CTor 采用 UCHAR
作为参数。 该参数可以具有各种枚举的值(所有枚举都保证适合 UCHAR
)。 我需要将这些值转换为 UCHAR,因为库函数要求其参数为该类型。
我必须创建很多这样的消息对象,为了节省输入工作量,我使用了 boost::assign :
std::vector<CMyClass> myObjects;
boost::assign::push_back(myObjects)
(MemberOfSomeEnum)
(MemberOfSomeEnum);
std::vector<CMyClass> myOtherObjects;
boost::assign::push_back(myObjects)
(MemberOfAnotherEnum)
(MemberOfAnotherEnum);
上面的代码使用两个枚举成员中的每一个调用 CMessage Ctor然后将它们放入列表中。 我的问题是,此代码在 VC++9 上引发警告 C4244(从枚举转换为 UCHAR 期间可能会丢失数据)。
我当前的解决方案是为每个枚举类型创建一个转换函数:
static UCHAR ToUchar(const SomeEnum eType)
{
return static_cast<UCHAR>(eType);
}
static UCHAR ToUchar(const AnotherEnum eType)
{
return static_cast<UCHAR>(eType);
}
然后上面的代码如下所示:
std::vector<CMyClass> myObjects;
boost::assign::push_back(myObjects)
(ToUchar(MemberOfSomeEnum))
(ToUchar(MemberOfSomeEnum));
std::vector<CMyClass> myOtherObjects;
boost::assign::push_back(myObjects)
(ToUchar(MemberOfAnotherEnum))
(ToUchar(MemberOfAnotherEnum));
这是迄今为止我能想到的最干净的方法。
有没有更好的办法?
也许 boost 能提供一些不错的东西?
我不想使用 pragma 语句禁用警告,并且无法修改枚举。
I created a class CMyClass
whose CTor takes a UCHAR
as argument. That argument can have the values of various enums (all guaranteed to fit into a UCHAR
). I need to convert these values to UCHAR
because of a library function demanding its parameter as that type.
I have to create a lot of those message objects and to save typing effort I use boost::assign
:
std::vector<CMyClass> myObjects;
boost::assign::push_back(myObjects)
(MemberOfSomeEnum)
(MemberOfSomeEnum);
std::vector<CMyClass> myOtherObjects;
boost::assign::push_back(myObjects)
(MemberOfAnotherEnum)
(MemberOfAnotherEnum);
The above code calls the CMessage
CTor with each of the two enum members and then puts them in a list.
My problem is, that this code throws the warning C4244 (possible loss of data during conversion from enum to UCHAR) on VC++9.
My current solution is to create a conversion function for each enum type:
static UCHAR ToUchar(const SomeEnum eType)
{
return static_cast<UCHAR>(eType);
}
static UCHAR ToUchar(const AnotherEnum eType)
{
return static_cast<UCHAR>(eType);
}
And then the above code looks like this:
std::vector<CMyClass> myObjects;
boost::assign::push_back(myObjects)
(ToUchar(MemberOfSomeEnum))
(ToUchar(MemberOfSomeEnum));
std::vector<CMyClass> myOtherObjects;
boost::assign::push_back(myObjects)
(ToUchar(MemberOfAnotherEnum))
(ToUchar(MemberOfAnotherEnum));
This is the cleanest approach I could think of so far.
Are there any better ways?
Maybe boost has something nice to offer?
I don't want to disable warnings with pragma statements and I cannot modify the enums.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不会在这里对 static_cast 感到尴尬,但如果你是:
节省为每个枚举编写一个函数。
I wouldn't be emabarrassed by static_cast here, but if you are:
saves writing a function for every enum.