I´m creating a custom ArrayList/Vector class and I´m having troubles creating an emplace_back function. How can I create arguments that are the same as the constructor of the "value_type class" of the ArrayList ?
-
Post what you have tried. If you dont post code we cant tell you whats wrong with your code, and were not going to write the code for you. – DetectivePikachu Nov 15 '19 at 16:47
-
`emplace_back` member functions aren't generated based on the contained type. They are just template member functions whose arguments are deduced to be those provided when used. It's up to the user to make sure those arguments make sense for constructing a new element. – François Andrieux Nov 15 '19 at 16:48
-
TBH, I don't understand the downvotes. This is a reasonable question IMO. And no, it doesn't require code, any attempt to write such function without knowledge how to do so will be wildly different from the solution and therefore irrelevant. – Yksisarvinen Nov 15 '19 at 16:52
-
Read up on [std::forward](https://en.cppreference.com/w/cpp/utility/forward) and "perfect forwarding" in general. – Jesper Juhl Nov 15 '19 at 16:58
1 Answers
emplace_back
and similar functions (std::make_shared
etc.) don't need to know anything about value_type
they are trying to contruct. This is possible thanks to parameter packs introduced in C++11.
Using parameter pack, you can make a function that takes any number of arguments (with any types).
Assuming that you have push_back
implemented, emplace_back
may look like this:
template<class... Args>
void emplace_back(Args&&... args)
{
push_back(value_type(args...));
}
There is a catch however. Passing arguments around can change their type (especially when we're dealing with move semantics: r-value reference will become l-value reference when passed to another function). This may be undesireable - user may overload methods to do different things when l-value or r-value passed.
That's where perfect forwarding with std::forward
comes in. Using std::forward
, we may pass the arguments further exactly like they were passed into your function.
template<class... Args>
void emplace_back(Args&&... args)
{
push_back(value_type(std::forward<Args>(args)...));
}
See my (very bad) example of it working: https://wandbox.org/permlink/KyQJU8rd2FGTTFLJ

- 18,008
- 2
- 24
- 52