C++宏代码 - 显式整数(任何大小)转换为指针类型
C++ Macro Code - Explicit integer (of any size) conversion to a pointer type
问题:我正在与具有预先存在的宏的 AVR 代码接口......
#define pgm_read_float_near(address_short) foo
它用于将uint16_t
值作为指针,获取它,然后返回float
值。我使用的是具有平面地址空间的 x86 处理器,我只需要这个宏来尊重指针。我的目标是在取消引用之前从uint16_t
非常明确地转换为float *
。
当前解决方案:
#define pgm_read_float_near(address_short) *reinterpret_cast<float *>(reinterpret_cast<void *>(NULL) | static_cast<uint16_t>(address_short))
我试图做什么..
-
static_cast
提供给宏的任何变量(不是类型安全(作为我期待的uint16_t -
OR
该值,并带有"NULL
指针",以"干净利落地"将uint16_t
扩展到uint32_t
-
reinterpret_cast
OR
的结果回到float *
- 最后,尊重获取
float
值的float *
。
问题:
- 我忘记了任何步骤吗?
- 我是否在做任何不必要的步骤,为什么?
注意:在你说"宏太可怕了!我别无选择,我正在现有的框架中工作......
由于您使用的是C++,因此我建议使用C++模板:
#include <stdio.h>
#include <stdint.h>
template<class Ty>
float *explicit_cast(Ty t) {
return 2;
}
template<>
float *explicit_cast<uint16_t>(uint16_t t) {
return reinterpret_cast<float *>(t);
}
#define pgm_read_float_near(address_short) explicit_cast(address_short)
void t8() {
uint8_t f8 = 2;
pgm_read_float_near(f8);
}
void t16() {
uint16_t f16 = 2;
pgm_read_float_near(f16);
}
void t32() {
uint32_t f32 = 2;
pgm_read_float_near(f32);
}
通过编译程序,您可以看到以下输出:
$ g++ cast.cpp -c
cast.cpp: In instantiation of ‘float* explicit_cast(Ty) [with Ty = unsigned char]’:
cast.cpp:18:5: required from here
cast.cpp:6:12: error: invalid conversion from ‘int’ to ‘float*’ [-fpermissive]
cast.cpp: In instantiation of ‘float* explicit_cast(Ty) [with Ty = unsigned int]’:
cast.cpp:28:5: required from here
cast.cpp:6:12: error: invalid conversion from ‘int’ to ‘float*’ [-fpermissive]
从其他类型的强制转换将引入编译错误。原理是我们可以使用该模板来区分uint16_t和其他类型。
相关文章:
- 无法转换类型 C++
- 包含可变参数包的第一个可转换类型的别名的结构
- 将 std::conditional 与不可转换类型(原始与指针)一起使用
- 链接方法时出现转换类型错误
- 如何避免隐式转换类型
- 在多重继承场景中动态强制转换类型
- 编译器不支持的转换类型
- 错误调用功能无法转换类型
- 我想看到一个在整个后缀表达式的上下文中查找转换类型 id 的示例
- 对于动态类型为强制转换类型的对象,dynamic_cast失败
- 无法在初始化中转换类型
- 如何让"auto"转换类型
- 如何通过强制转换类型指针将字符数组转换为uint16_t
- 如何从新运算符+(Template类)返回具有转换类型的对象
- 带有模板的基于枚举的工厂无法转换类型
- 使用SWIG类型映射通过字符串转换类型
- 对于可转换类型,设计比循环依赖项更好
- SWIG不能正确转换类型定义
- 将类型转换扩展到可转换类型的对/元组
- 想要将字符数组的部分转换/类型转换为值