您的位置:首页 > 编程语言 > C语言/C++

C++ tuple 速记

2015-08-11 13:00 831 查看

简介

tuple 是C++11 以模板的形式开发的元组, 类似于pair , 但是支持任意的元素个数。

基本的操作

int main ()
{
/*** Construct a tuple ***/
// By constrcut
std::tuple<int,char> foo (10,'x');
// By make_tuple
auto bar = std::make_tuple ("test", 3.1, 14, 'y');
// By forward_as_tuple
auto ref = std::forward_as_tuple(std::string("test") + "eee" , 1, 'a');

/*** Assign ***/
std::get<2>(bar) = 100;

/*** Get type and get value ***/
std::tuple_element<0,decltype(bar)>::type bar_1 = std::get<0>(bar);

/*** unpack a tuple ***/
int myint; char mychar;
std::tie (myint, mychar) = foo;                            // unpack elements
std::tie (std::ignore, std::ignore, myint, mychar) = bar;  // unpack (with ignore)
/*** get size as a type **/
std::cout << std::tuple_size<decltype(bar)>::value << "\n";
auto merge = std::tuple_cat(foo,bar);
return 0;
}


可以看到 , tuple的构造是比较灵活的, 可以提前声明具体实例化类型, 也可以交由编译器根据构造

参数推导。

forward_as_tuple
似的tuple对右值有较好的支持。

std::tie
std::ignore
std::get
之外提供了获取tuple内部元素的方式,且

支持批量获取。

在将一个tuple视为一种特定类型的时候 :

tuple_element
提供了获取对应元素的类型的途径。

tuple_size
提供了获取tuple类型大小的途径。

std::tuple_cat
提供了合并tuple为一个tuple的途径

尚未有截断tuple的直接接口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: