Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Uniform initialization for pair and tuple

📅 2014-Nov-05 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, pair, tuple, uniform initialization ⬩ 📚 Archive

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

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧