Reputation: 2198
I am upgrading an application from using libpqxx 7.1.2
to 7.3.1
and one of the things that have changed in the meantime is that pqxx::binarystring
has been deprecated in favour of std::basic_string<std::byte>
.
My issue is that I use std::vector<uint8_t>
in C++ to represent a SHA-1 hash, which I then need to store in Postgress as BYTEA. So now I need to find a way to convert std::vector<uint8_t>
to std::basic_string<std::byte>
and back.
But I have been unable to find a way to get from vector -> string.
I have been looking at the constructor for std::basic_string<T>
and simply cannot figure out how to do it.
Amongst other ways to construct std::basic_strig<T>
I have tried this, but all give compiler errors error: no matching constructor for initialization of 'std::basic_string<std::byte>'
.
But when I look at the documentation, I thought the different options I have tried should be legal. So how do I achieve this?
#include <string>
#include <vector>
#include <cstdint>
#include <cstddef>
int main(void)
{
std::vector<uint8_t> data = {1, 2, 3, 4};
std::basic_string<std::byte> a(std::begin(data), std::end(data));
std::basic_string<std::byte> b((char*)data.data(), data.size());
}
Upvotes: 1
Views: 1326
Reputation: 26196
It is strange that they have chosen a basic_string
instead of a vector
for this, but this works:
std::basic_string<std::byte> a(
static_cast<const std::byte *>(static_cast<const void *>(data.data())),
data.size()
);
It should be fine because uint8_t
is trivially copyable and std::byte
pointers can alias others.
Upvotes: 2