Uniform initialization for pair and tuple

The uniform initialization syntax introduced in C++11 makes a lot of C++ code less verbose and thus easier to type and read.

For example, constructing a pair used to required std::make_pair(), but can now be done directly using the uniform initialization syntax:

#include <unordered_map>
std::unordered_map<int, std::pair<double, char>> umap;

// Verbose old method
umap.insert(std::make_pair(10, std::make_pair(3.14, 'p')));

// Using uniform initialization
umap.insert({10, {3.14, 'p'}});

Sadly, the same syntax cannot be used for tuple, where it would really come in handy! 😦

#include <unordered_map>
std::unordered_map<int, std::tuple<double, char, int>> umap;

// Verbose old method
umap.insert(std::make_pair(10, std::make_tuple(3.14, 'p', 999)));

// Using uniform initialization
// Error:
// converting to const std::tuple<float, char> from initializer list would use explicit constructor
umap.insert({10, {3.14, 'p', 999}});

The reason for this is answered here.

Tried with: GCC 4.9.1 and Ubuntu 14.04

Advertisements

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