use*_*087 3 c++ casting reference
我尝试将int8_t的引用转换为uint8_t的引用.
我有以下代码:
inline mtype& operator&(mtype& mt, uint8_t& va) {
// do something
// ...
return mt;
}
inline mtype& operator&(mtype& mt, int8_t& va) {
// do the same but signed
// ...
return mt;
}
Run Code Online (Sandbox Code Playgroud)
因为这两种重载做同样的,我要干(或更好的DRM),所以我想打电话与第一运营商casted va.但是我该怎么做?这不行.
inline mtype& operator&(mtype& mt, int8_t& va) {
return mt& static_cast<uint8_t>(va); // error: no match for 'operator&' in 'mt & (uint8_t)va'
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
您想重新解释数据是什么.
inline mtype& operator&(mtype& mt, int8_t& va) {
return mt& reinterpret_cast<uint8_t&>(va);
}
Run Code Online (Sandbox Code Playgroud)
但要小心.根据"执行相同但已签名"的含义,您可能无法通过调用相同的函数来执行正确的操作并假设数据始终是无符号的.
如果您的代码正在执行具有唯一签名/无符号逻辑的工作(尽管代码看起来相同),您将需要使用模板函数来生成正确的特定于类型的逻辑.
template< Typename T >
mtype& do_the_work( mtype& mt, T& va )
{
// do something
// (Here's an example of code that LOOKS the same, but doesn't DO the same)
va = va >> 1;
}
inline mtype& operator&(mtype& mt, uint8_t& va) {
return do_the_work( mt, va );
}
inline mtype& operator&(mtype& mt, int8_t& va) {
return do_the_work( mt, va );
}
Run Code Online (Sandbox Code Playgroud)