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

3
我试图将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),因此我想使用转换后的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个回答

6
您希望重新解释数据是什么。
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 );
}

你应该严格注意,在一个假设的系统中,如果这些类型不仅仅是typedef为char类型,那么reinterpret_cast将违反严格别名规则。 - Mark B

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

1
你遇到的错误是由于转换导致值而不是引用。
你应该使用:
reinterpret_cast<uint8_t&>(va)

@MikeSeymour 对,我的错。 - syam

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接