Variadic Templates – example that simplifies populating a vector

I was hoping that Visual Studio 2012 would allow us to initialise a std::vector; like this, especially with the November CTP:

std::vector<int> items = { 1, 2, 3, 4, 5 };

However, although the November CTP includes support for variadic templates and uniform initialisation, they haven’t yet decorated all standard templates with initializer lists as needed for the above. That tempted me to write a simple variadic template to avoid having to write code like this ever again:

std::vector<int> items;
items.push_back(0);
items.push_back(1);
items.push_back(2);

By writing this:

namespace musingstudio
{
  template<typename T, typename U, typename ...Args>
  void push_back(std::vector<T>& items, U item, Args ...args)
  {
    items.push_back(item);
    push_back( items, args... );
  }

  template<typename T, typename U>
  void push_back(std::vector<T>& items, U item)
  {
    items.push_back(item);
  }
}

We can then write this:

std::vector<int> items;
musingstudio::push_back( items, 0,1,2,3,4,5 );

Obviously, this is less efficient than implementing a constructor that takes initializer lists, but it’s more fun than repeatedly typing push_back the C++98/03 way.

Leave a comment

Filed under C++ Code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s