简体   繁体   中英

How do I avoid compiler warnings when converting enum values to integer ones?

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.

I wouldn't be emabarrassed by static_cast here, but if you are:

template <class T>
inline UCHAR ToUchar(T t)
{
    return static_cast<UCHAR>(t);
}

saves writing a function for every enum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM