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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…