castingmfccarchive

Reading a WORD variable from a CArchive and casting to int at the same time


This might sound basic but:

WORD wSong = 0;
CArchive ar;
...
ar >> wSong;
m_sPublicTalkInfo.iSongStart = static_cast<int>(wSong);

At the moment I read the WORD into a specific variable and the cast it.

Can I read it in and cast at the same time?

Please note I can't serialize a int. It must be a WORD and cast to int. Or

ar >> wSong;
m_sPublicTalkInfo.iSongStart = static_cast<int>(wSong);

Solution

  • I don't think there is a direct way. You could implement a helper function:

    template <typename T, typename U>
    T readAndCast (CArchive& ar) {
      U x;
      ar >> x;
      return static_cast<T> (x);
    }
    
    
    m_sPublicTalkInfo.iSongStart = readAndCast<int, WORD>(ar);
    

    It might be better to use the fixed-width integer types in your program, i.e. perhaps int_least16_t instead of int to be sure the type has the right size. WORD is fixed to 16bit, but int isn't. Also, WORD is unsigned and int isn't, so there could be an overflow during casting.