1

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)... ) );
}
ildjarn
  • 62,044
  • 9
  • 127
  • 211

2 Answers2

5

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.

Stephan Dollberg
  • 32,985
  • 16
  • 81
  • 107
2

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

However, push_back does support initializer lists:

v.push_back({1,2});
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • This is exactly what I want. Do any compilers support this syntax yet? It looks like `{}` isnt supported by MSVC yet –  Feb 23 '13 at 18:06
  • Try the example at http://stackoverflow.com/a/10890716/1204143 and see if it will compile. (If not, then MSVC is not yet C++11 compliant and you will have to use `emplace_back`). – nneonneo Feb 23 '13 at 18:10
  • it doesnt. Does GCC support that? I dont have it installed or maybe i have an old version –  Feb 23 '13 at 18:18
  • Works on my version of Clang, so I suspect this is just an unimplemented feature in MSVC. – nneonneo Feb 23 '13 at 19:37