如何将对int8_t的引用转换为对uint8_t的引用
how to cast a reference to int8_t to a reference to uint8_t?
我尝试将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'
}
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?