simpleroseinc

Logo

Developer Tips

View Company GitHub Profile

22 May 2020

CTAD for tuple-like types

by Zhihao Yuan

The standard library has three tuple-like1 types: std::tuple, std::pair, and std::array. You can create objects of them by referencing only their class template names thanks to Class Template Argument Deduction:

using namespace std::string_literals;

auto tup = std::tuple(3, 1.0, false);  // std::tuple<int, double, bool>
auto pr  = std::pair("nice"s, 3L);     // std::pair<std::string, long>
auto arr = std::array{ 0.1, 2., 4. };  // std::array<double, 3>

The above is equivalent to:

std::tuple tup(3, 1.0, false);
std::pair  pr("nice"s, 3L);
std::array arr{ 0.1, 2., 4. };

If you still remember std::make_tuple and std::make_pair introduced in C++11, we don’t need them in non-generic code unless you are creating tuple of references.

As a matter of fun, std::tuple() creates an object of std::tuple<>. Does this remind you of the empty tuple () in Python?


1std::get<N>(obj) can be used for getting the Nth element in an object of a tuple-like type.

tags: cplusplus - class-template-argument-deduction - tuple