Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
238 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...