I have used vector::emplace_back in order to avoid constructing temporal objects while filling a vector. Here you have a simplified version:
class Foo {
public:
Foo(int i, double d) : i_(i), d_(d) {}
/* ... */
};
std::vector<Foo> v;
v.reserve(10);
for (int i = 0; i < 10; i++)
v.emplace_back(1, 1.0);
But I wanted to use std::fill_n instead:
v.reserve(10);
std::fill_n(std::back_inserter(v), 10, Foo(1, 1.0));
In this way, temporal copies will be created, though. I do not know how to use emplace in this situation. I guess I would need something like std::back_emplacer, but I could not find such a thing. Is that part of C++11, but not implemented in GCC yet? If it is not part of C++11, is there any other way to do that?
It’s common to use tuples to ease the pass a variadic number of items (in this case, parameters to forward to
emplace_back), with a little technique to unpack the tuple back. As such it is possible to write aback_emplacerutility by requiring the user to make use of the tuple factory functions (one ofstd::make_tuple,std::tie,std::forward_as_tuple) where it make sense:A demonstration of the code is available. In your case you’d want to call
std::fill_n(back_emplacer(v), 10, std::forward_as_tuple(1, 1.0));(std::make_tupleis also acceptable). You’d also want the usual iterator stuff to make the feature complete — I recommend Boost.Iterators for that.I must really stress however that such a utility doesn’t bring much when used with
std::fill_n. In your case it would save the construction of the temporaryFoo, in favour of a tuple of references (a tuple of values if you were to usestd::make_tuple). I leave it to the reader to find some other algorithm whereback_emplacerwould be useful.