C++11: std::tuples

C++11: std::tuples

std::tuple Tutorial & Examples

what is std::tuple and why do we need it

std::tuple是一种可以将固定大小的异构值绑定在一起的类型。在创建元组对象时,我们需要将元素的类型指定为模版参数。

Creating a std::tuple object

首先是要include进头文件:

1
#include <tuple>

我们可以声明一个包含了int, double和string类型的tuple,实际上这种做法可以帮助我们从一个函数中返回多种值,避免创建不必要structure。

1
std::tuple<int, double, std::string> result(7, 9.8, "text");

Getting elements from a std::tuple

我们可以使用std::get函数获得隐藏在tuple对象中的元素,方法是将索引值指定为模版参数:

1
int iVal = std::get<0>(result);

Getting Out Of Range value from tuple

从tuple中获取索引大于元素数量的tuple元素会引起编译错误:

1
int iVal2 = std::get<4>(result); // Compile error

Wrong type cast while getting value from tuple

接收类型与tuple里面元素不符合也会导致编译错误:

1
std::string strVal2 = std::get<0>(result); // Compile error

Getting value from tuple by dynamic index

提供给std::get的模版参数必须是编译期常量,否则会引起编译错误:

1
2
3
4
5
6
int x = 1;
double dVal2 = std::get<x>(result); // Compile error

const int i = 1;
// Get second double value from tuple
double dVal3 = std::get<i>(result);

make_tuple Tutorial & Example

Initializing a std::tuple

我们可以通过传递参数到构造器的方式来初始化std::tuple:

1
std::tuple<int, double, std::string> result1 { 22, 19.28, "text" };

但tuple无法自动去推断类型:

1
2
auto result { 22, 19.28, "text" }; // Compile error
// error: unable to deduce ‘std::initializer_list<_Tp>’ from ‘{22, 1.9280000000000001e+1, "text"}’

于是C++11提供了std::make_tuple来解决这个问题:

std::make_tuple

std::make_tuple可以通过自动推断元素的类型来创建std::tuple对象:

1
auto result2 = std::make_tuple( 7, 9.8, "text" );