std::byte
is a new type in C++17 which is made as enum class byte : unsigned char
. This makes impossible to use it without appropriate conversion. So, I have made an alias for the vector of such type to represent a byte array:
using Bytes = std::vector<std::byte>;
However, it is impossible to use it in old-style: the functions which accept it as a parameter fail because this type can not be easily converted to old std::vector<unsigned char>
type, for example, a usage of zipper
library:
/resourcecache/pakfile.cpp: In member function 'utils::Bytes resourcecache::PakFile::readFile(const string&)':
/resourcecache/pakfile.cpp:48:52: error: no matching function for call to 'zipper::Unzipper::extractEntryToMemory(const string&, utils::Bytes&)'
unzipper_->extractEntryToMemory(fileName, bytes);
^
In file included from /resourcecache/pakfile.hpp:13:0,
from /resourcecache/pakfile.cpp:1:
/projects/linux/../../thirdparty/zipper/zipper/unzipper.h:31:10: note: candidate: bool zipper::Unzipper::extractEntryToMemory(const string&, std::vector<unsigned char>&)
bool extractEntryToMemory(const std::string& name, std::vector<unsigned char>& vec);
^~~~~~~~~~~~~~~~~~~~
/projects/linux/../../thirdparty/zipper/zipper/unzipper.h:31:10: note: no known conversion for argument 2 from 'utils::Bytes {aka std::vector<std::byte>}' to 'std::vector<unsigned char>&'
I have tried to perform naive casts but this does not help also. So, if it is designed to be useful, will it be actually useful in old contexts? The only method I see is to use std::transform
for using new vector of bytes in these places:
utils::Bytes bytes;
std::vector<unsigned char> rawBytes;
unzipper_->extractEntryToMemory(fileName, rawBytes);
std::transform(rawBytes.cbegin(),
rawBytes.cend(),
std::back_inserter(bytes),
[](const unsigned char c) {
return static_cast<std::byte>(c);
});
return bytes;
Which is:
- Ugly.
- Takes a lot of useless lines (can be rewritten but still it needs to be written before:)).
- Copies the memory instead of just using already created chunk of
rawBytes
.
So, how to use it in old places?