The following function template tries to locate an object in an array of bytes.
We may assume that the argument buffer
“usually” holds an object of the given type, but I need a diagnostic (assertion check) against possible errors.
template <typename T>
T* get_object_from_buffer(std::uint8_t* buffer, std::size_t size)
{
void* tmp_buffer = buffer;
if (nullptr != std::align( alignof(T),
sizeof(T),
tmp_buffer,
size ) )
{
return reinterpret_cast<T*>(buffer);
}
else
{
// Caller can check returned pointer to implement diagnostic reactions
return nullptr;
}
}
Questions:
-
Is it allowed (and portable) to do this using
std::align
? -
Do you see a better solution – more robust, more elegant?
Conditions:
-
The function will be used on an embedded system.
Hence, some google hits for std::align usage on PC platforms are not applicable. -
Buffer is filled by a function like the following:
template <typename T> std::pair<std::uint8_t*, std::size_t> put_object_into_buffer(T* object) { return std::pair<std::uint8_t*, std::size_t>( reinterpret_cast<std::uint8_t*>(object), sizeof(object) ); }
Between the put/get functions, I have to pass the buffer through a library that is not
aware of user-defined types likeT
.