简体   繁体   中英

vector push_back with forwarding?

I do something like this in my code

S s;
s.a=1
s.b=2
v.push_back(s)

Now that C++ has forwarding can i write something like

v.push_back(1,2)

fyi visual studio supports forwarding as the below works as expected

//http://herbsutter.com/gotw/_102/
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
    return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}

You can use std::vector::emplace_back which will create the object inplace with the fitting constructor. This of course requires that you have such a constructor defined.

v.emplace_back(1,2);

As of C++11 every std-container offers an emplace-like function which gives the above described behavior.

Compatibility-note: MSVC probably doesn't support this yet as it only supports variadic templates as of the CTP which doesn't affect the standard library and gcc's libstd++ is still missing the emplace member functions in the associative containers.

push_back doesn't support forwarding, but the new emplace_back does.

However, push_back does support initializer lists:

v.push_back({1,2});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM