Well... I suppose you could use reserve()
one time and then add the single element using push_back()
.
The following example use int
instead of class A
but should give the idea
#include <vector>
#include <iostream>
template <typename T>
void appendT (std::vector<T> & v)
{ }
template <typename T, typename ... Ts>
void appendT (std::vector<T> & v, T t, Ts ... ts)
{
v.push_back(t);
appendT(v, ts...);
}
template <typename T, typename ... Ts>
void appendTs (std::vector<T> & v, Ts ... ts)
{
v.reserve(v.size() + sizeof...(Ts));
appendT(v, ts...);
}
int main()
{
std::vector<int> v { 2, 3, 5 };
appendTs(v, 7, 11, 13, 17);
for ( auto const & i : v )
std::cout << ' ' << i; // print " 2 3 5 7 11 13 17"
std::cout << std::endl;
}
If you don't like the recursive solution, you can write an appendTs()
that do all the works (but I don't know how to avoid the annoing "warning: unused variable 'unused'" I know how to avoid the warning but I don't know if it's a good idea Kuba Ober suggested me an elegant way to avoid the warning)
#include <vector>
#include <iostream>
template <typename T, typename ... Ts>
void appendTs (std::vector<T> & v, Ts ... ts)
{
v.reserve(v.size() + sizeof...(Ts));
// the first '0' is to avoid an error when sizeof...(Ts) is zero
char unused[] { '0', (v.push_back(ts), '0')... };
// the following statement is to avoid an annoing "unused variable
// 'unused'" warning (thanks Kuba Ober)
(void)unused;
}
int main()
{
std::vector<int> v { 2, 3, 5 };
appendTs(v, 7, 11, 13, 17);
for ( auto const & i : v )
std::cout << ' ' << i; // print " 2 3 5 7 11 13 17"
std::cout << std::endl;
}