Reputation: 70108
Let's assume I have a non-STL vector type that is compatible with std::vector by an operator std::vector<T>
. Is it possible to move its elements to a std::vector instead of the default copy construction, so that
OtherVectorType<SomeClass> f()
{
OtherVectorType<SomeClass> v;
v.pushBack(SomeClass());
v.pushBack(SomeClass());
v.pushBack(SomeClass());
return v;
}
std::vector<SomeClass> sv = f();
would use SomeClass's move constructor (3 times) when creating the std::vector sv
?
I imagine something like
template<typename T>
std::vector<T>& operator= (std::vector<T>& self, OtherVectorType<T>&& from)
{
[...]
}
but haven't found any working solution yet.
For illustration, this is how the std::vector operator is defined:
template<typename T> class OtherVectorType
{
[...]
operator std::vector<T>() const
{
if (!m_size)
return std::vector<T>();
return std::vector<T>(reinterpret_cast<T*>(m_pElements),
reinterpret_cast<T*>(m_pElements) + m_size);
}
}
Upvotes: 2
Views: 529
Reputation: 218700
The easiest thing to do (especially if you don't have rvalue-this) is to make use of make_move_iterator
as demonstrated below:
#include <deque>
#include <vector>
#include <memory>
#include <iterator>
typedef std::unique_ptr<int> SomeClass;
typedef std::deque<SomeClass> OtherVectorType;
OtherVectorType
f()
{
OtherVectorType v;
v.push_back(SomeClass(new int (1)));
v.push_back(SomeClass(new int (2)));
v.push_back(SomeClass(new int (3)));
return v;
}
std::vector<SomeClass>
to_vector(OtherVectorType&& o)
{
return std::vector<SomeClass>(std::make_move_iterator(o.begin()),
std::make_move_iterator(o.end()));
}
int main()
{
std::vector<SomeClass> v = to_vector(f());
}
Upvotes: 2
Reputation: 56863
I think you need support for rvalue references for *this
.
operator std::vector<T>() const &; // copy your own type's data
operator std::vector<T>() &&; // move it into the std::vector<T>
Sadly, support is rare, even GCC 4.8 does not have it. :(
Upvotes: 5