Is it possible to move a vector into a vector of different type?

Viewed 80

Assume, I have two functions that work with arguments that are vectors of different types:

void foo(const std::vector<SomeType>& v);
void bar(const std::vector<std::byte>& v);

What if in some place of my code I want to pass the same vector object to both of these functions? Obviously, I cannot just cast a vector of one type to a vector of different type, so I have to create a second vector:

const std::vector<SomeType> v(...);
foo(v);
// v is not needed anymore
const auto vSizeBytes = v.size() * sizeof(SomeType);
std::vector<std::byte> v2;
v2.resize(vSizeBytes);
std::memcpy(&v2[0], &v[0], vSizeBytes);
bar(v2);

But if I know for sure that v is not needed anymore after calling foo(v), I want move instead of copy. Is there any alternative to std::memcpy() for moving the original data of a container into another container instead of copying it?

1 Answers

You can use templates. Assuming the code in the function will work on both types.

template<class SOMETYPE> void foo(const std::vector<SOMETYPE>& v);
template<class SOMETYPE> void bar(const std::vector<SOMETYPE>& v);
Related