我尝试将 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;
}
因为两个重载都做同样的事情,所以我想 dry (或更好的 drm),所以我想用 casted va
调用第一个运算符(operator)。但我该怎么做呢?这行不通。
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'
}
我该怎么做才对?
最佳答案
您想重新解释数据是什么。
inline mtype& operator&(mtype& mt, int8_t& va) {
return mt& reinterpret_cast<uint8_t&>(va);
}
不过要小心。根据“做同样的事情但已签名”的含义,您可能不会通过调用相同的函数并假设数据始终未签名来做正确的事。
如果您的代码正在执行具有独特的有符号/无符号逻辑的工作(尽管代码看起来相同),您将需要使用模板函数来生成正确的特定于类型的逻辑。
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 );
}
关于c++ - 如何将对 int8_t 的引用转换为对 uint8_t 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16093599/