Search code examples
c++arrayliststdvectorpush-backemplace

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 ?


Solution

  • 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