C++用于在指向相同大小类型的指针之间进行转换

C++ cast for casting between pointers to types of the same size?

本文关键字:指针 类型 之间 转换 小类 用于 C++      更新时间:2023-10-16

假设我们有这个签名:

void frobnicate(const uint8_t* raw_memory, size_t bytes);

是否可以编写一个C++转换函数,该函数将允许将任意类型(例如,uint_least8_tsigned 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
缺点:诊断更详细一些

相关文章: