Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c++ - How to create an emplace_back method?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...