vector::emplace_back multiple items
{ text has been reformatted to ~70 chars per line. -mod }
I came up with the following solution to work around the fact that
vector::emplace_back allows the insertion of only one single element
at a time.
My requirements are the use of a move-only type (see struct A below),
so the initializer_list version of the vector ctor is a no-go.
Following is i) the definition of the A type, ii) the template functions
implementing the logic, iii) a sample main function.
#include <iterator>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
template<typename Container, typename Element>
void emplace_all_helper(Container& c, Element&& e) {
c.emplace_back(forward<Element>(e));
}
template<typename Container, typename Element, typename ...Elements>
void emplace_all_helper(Container& c, Element&& e, Elements&&... args) {
emplace_all_helper(c, forward<Element>(e));
emplace_all_helper(c, forward<Element>(args)...);
}
template<typename Container, typename ...Elements>
void emplace_all(Container& c, Elements&&... args) {
c.reserve(c.size() + sizeof...(args));
emplace_all_helper(c, forward<Elements>(args)...);
}
struct A {
int m_v;
A(int v) : m_v {v} { }
A(A&& other) noexcept { m_v = other.m_v; }
A& operator=(A&& other) noexcept { m_v = other.m_v; return *this; }
A() = delete;
A(const A& other) = delete;
A& operator=(const A& other) = delete;
};
ostream& operator<<(ostream& os, const A& a) {
os << a.m_v;
return os;
}
int main() {
vector<A> va;
emplace_all(va, A(1), A(2), A(3));
copy(begin(va), end(va), ostream_iterator<A>(cout, ", ")); // prints 1,
2, 3,
cout << endl;
}
Does anybody have an alternative / better idea how to achieve something
similar?
Thanks,
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]