如何将对int8_t的引用转换为对uint8_t的引用

how to cast a reference to int8_t to a reference to uint8_t?

本文关键字:引用 uint8 转换 int8      更新时间:2023-10-16

我尝试将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;
}

因为两个重载都做同样的事情,我想要干燥(或更好的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'
}

我该怎么做呢?

您需要重新解释数据是什么

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 );
}
inline mtype& operator&(mtype& mt, int8_t& va) {
  return mt & reinterpret_cast<uint8_t&>(va);
}

得到的错误是因为强制转换得到的值不是引用。

你应该使用:

reinterpret_cast<uint8_t&>(va)

你的问题是你正在转换为非const值,但你的函数期望非const引用。

几乎可以肯定,真正想要的是操作符接受第二个参数的值(如果你的operator&真的改变了它的右手操作符,你需要重新考虑你的操作符):

inline mtype& operator&(mtype& mt, uint8_t va) {
  // do something
  // ...
  return mt;
}
inline mtype& operator&(mtype& mt, int8_t va) {
  return mt& static_cast<uint8_t>(va); //  error: no match for 'operator&' in 'so & (uint8_t)va'
}