C++用于在指向相同大小类型的指针之间进行转换
C++ cast for casting between pointers to types of the same size?
假设我们有这个签名:
void frobnicate(const uint8_t* raw_memory, size_t bytes);
是否可以编写一个C++转换函数,该函数将允许将任意类型(例如,uint_least8_t
或signed char
等)转换为uint8_t*
以馈送到该函数中?
所有标准选件都是reinterpret_cast
的,当然,这将从任何指针类型投射。
通过示例:
std::vector<int> iv = ...;
std::vector<char> cv = ...;
frobnicate(sized_ptr_cast<const uint8_t*>(iv.data()), iv.size()); // must not compile
frobnicate(sized_ptr_cast<const uint8_t*>(cv.data()), cv.size()); // should compile
基本上是一个有一些限制的reinterpret_cast
。
免责 声明:
- 请撇开
f(T*, size_t len)
是否是一个好的接口以及如何更好地使用基于迭代器的接口等。 - 请不要
void*
(? -
CHAR_BIT == 8
这是一个包装reinterpret_cast
并用static_assert
约束它的实现
template <typename T, typename U>
T sized_ptr_cast(U *p) {
static_assert(std::is_pointer<T>::value, "");
static_assert(sizeof(typename std::remove_pointer<T>::type) == sizeof(U), "size must be same");
return reinterpret_cast<T>(p);
}
http://coliru.stacked-crooked.com/a/d13da2471b051d5d
一个简单的模板函数按照您的要求执行,使用 std::pointer_traits
:
template<class T, class P> auto sized_ptr_cast(P&& p)
-> typename std::enable_if<sizeof(std::pointer_traits<T>::element_type)
== sizeof(std::pointer_traits<P>::element_type), T>::type
{ return reinterpret_cast<T>(p); }
与使用static_assert
相比的优势:使用SFINAE
缺点:诊断更详细一些
相关文章:
- C++中的双指针类型转换
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 将类指针类型转换为键时出错
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- C++在一个映射中存储不同的指针类型(并处理销毁)
- 指针类型类成员的动态强制转换的恒定性是什么?
- 我正在尝试将表的地址传递给要在另一个函数中使用的指针,但得到不兼容的指针类型
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- STL 函数和函数类型与函数指针类型
- 如何调用指针类型的方法(禁用多态性)?
- 为什么新表达式可以正确生成指针类型,即使它应该返回 void*?
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 是否允许调用方对我的 Builder 类使用任何指针类型(包括智能指针)?
- OPENCL 警告:不兼容的指针类型将'float __global[16]'传递给类型为 '__global float4 的参数 *
- 专门用于"direct"函数类型(与函数指针类型相对)
- 指向成员的指针类型和模板
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 在C++17中,为什么类模板和函数模板的指针类型推导明显不一致
- 为什么允许将整型、枚举和指向成员的指针类型reinterpret_cast到自身?