I have a struct representing a binary message. I want to write a function to get the next such record from a buffer (whether a file or a socket, doesn't matter):
template <typename Record>
Record getNext();
Now, I could write this like:
template <typename Record>
Record getNext() {
Record r;
populateNext(reinterpret_cast<char*>(&r), // maybe ::read()
sizeof(r)); // or equivalent
return r;
}
which is nice and gives me the benefits of RVO. However, it will invoke the default constructor of Record
, which may be composed of types with non-trival default constructors which do work that I would like to avoid - these are not necessarily POD types, but they are standard layout.
Is there a way to write getNext()
such that we avoid any constructors (default or copy/move) on Record
? Ideally, when the user calls:
auto record = getNext<Record>();
The buffer is read directly into the memory of record
. Is this possible?