C++11 has introduced emplace
function to construct an element in-place inside a sequence. This is complementary to insert
which either copies or moves elements.
However, out of several overloads of insert
, only the single element insert version,
i.e.
iterator insert( const_iterator p, T const& x);
iterator insert( const_iterator p, T&& x );
has an emplace
version,
template< class... Args >
iterator emplace(const_iterator p, Args&&... x);
Is there any reason, not to allow construction of n
elements in-place using emplace
?
While a overload like,
template< class... Args >
iterator emplace(const_iterator p,size_type n,Args&&... x);
just like the corresponding insert
iterator insert(const_iterator p,size_type n,const_reference x);
may conflict with the other overload, taking the constructor arguments as a tuple
, or using some special tag like in_place_t
likely to disambiguate them.
EDIT
The proposed function emplace_n
for vector
may have behaviour like the one given below
template<class... Args>
iterator emplace_n(const_iterator p,size_type n,Args&&... x)
{
size_type const offset = p - begin();
if(capacity() < size()+n)
{
vector<T> v;
v.reserve(size()+n);
v.assign(make_move_iterator(begin(),make_move_iterator(end());
swap(*this,v);
}
auto const sz = size();
for(auto c = 0; c != n ; ++c)
{
emplace_back(x...); //can do forward only if n == 1
}
rotate(begin()+offset,begin()+sz,end());
return iterator{begin() + offset};
}