从CArchive读取WORD变量并同时转换为int [英] 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);
此刻,我将 WORD
读入一个特定变量并将其强制转换.
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?
请注意,我无法序列化 int
.它必须是 WORD
,并强制转换为 int
.或者
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);
推荐答案
我认为没有直接的方法.您可以实现一个辅助函数:
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);
最好在您的固定字体中使用定宽整数类型程序,即使用 int_least16_t
而不是 int
来确保类型具有正确的大小. WORD
已已修复至16位,但不是 int
.另外, WORD
是无符号的,而 int
不是,因此在转换过程中可能会发生溢出.
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.
这篇关于从CArchive读取WORD变量并同时转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!