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

标签 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 调用第一个运算符(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/

相关文章:

c++ - 如何从 3D 点获取屏幕坐标? OpenGL

c++ - 非类型模板参数的类型转换无效

c++ - Mysql++ "undefined reference to __imp___ZN7mysqlpp10ConnectionC1Eb"

c++ - C++中的临时变量和常量有什么区别?

c++ - 如何将 uint8_t 放入 char 数组中?

c++ - 调试器不接收断点事件

C++调用时指定函数的非模板版本

c++ - libcvd - 编译 C++ 时未定义对 "x..."的引用

c# - Fundamental .NET - 如何引用 'stored/resolved'

c++ - 使用 cvflann::anyimpl::bad_any_cast 在 iOS 上拼接全景图会崩溃