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

时间:2013-04-18 21:42:40

标签: c++ reference casting

我尝试将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调用第一个运算符。但是我该怎么做?这不起作用。

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'
}

我该怎么做?

4 个答案:

答案 0 :(得分:6)

您希望重新解释数据是什么。

inline mtype& operator&(mtype& mt, int8_t& va) {
  return mt& reinterpret_cast<uint8_t&>(va);
}

但要小心。根据“执行相同但已签名”的含义,您可能无法通过调用相同的函数来执行正确的操作并假设数据始终未签名

如果您的代码 正在进行具有唯一签名/无符号逻辑的工作(尽管代码看起来相同),您将需要使用模板函数来生成正确的特定于类型的逻辑。 / p>

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 );
}

答案 1 :(得分:1)

inline mtype& operator&(mtype& mt, int8_t& va) {
  return mt & reinterpret_cast<uint8_t&>(va);
}

答案 2 :(得分:1)

您得到的错误是因为演员表导致的值不是参考值。

您应该使用:

reinterpret_cast<uint8_t&>(va)

答案 3 :(得分:0)

您的问题是您正在转换为非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'
}