Search code examples
c++pointersreinterpret-cast

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


Say we have this signature:

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

Is it possible to write a C++ casting function, that will allow casting an arbitrary type (say, e.g., uint_least8_t or signed char, ...) to an uint8_t* to feed into that function?

All the standard offers is reinterpret_cast and that will of course cast from any pointer type.

By example:

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

Basically a reinterpret_cast with some constraints.

Disclaimers:

  • Please leave aside whether f(T*, size_t len) is a good interface and how an iterator based interface would be better off etc.
  • No void* please (?) :-)
  • CHAR_BIT == 8

Solution

  • Here is an implementation that wrap reinterpret_cast and constrain it with 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