<tuple>库及其应用
(Danny Kalev发表于2004-12-27 16:11:06)
C++ 标准委员会正在进行标准库(Standard Library)的扩展工作。这个扩展包括一个新的tuple库。下面我将讨论这个库和它的应用。(目前标准库文件中还没有包含这个库,所以你需要从 Boost 下载它的源文件:http://sourceforge.net/project/showfiles.php?group_id=7586
1、何为 tuple?
Tuple 是一个大小固定的异构对象集合。Tuple 类型有很多有用的应用,比如封装一个函数的多个返回值以及模拟多个对象的同时赋值和比较。
Tuple 的大小是指它所包含的元素的个数。目前的 tuple 库支持 0-10 个元素的 tuple。每个元素可以是不同的类型。下面的例子创建一个具有两个元素(分别为 float 和 void *)和一个匹配初始化例程的 tuple。
#include <tuple>
tuple <float, void *> t(2.5, NULL);
如果忽略初始化例程,会使用默认的初始化过程:
tuple <double, string> t; //initialized to (0.0, string())
2、辅助函数
Tuple 库包括几个辅助函数,例如,make_tuple() 函数根据其参数实例化一个tuple类型:
voidfunc(int n);
make_tuple(func); // returns: tuple < void (*)(int) >
make_tuple("test", 9); // tuple < const char (&)[5], int >
tuple_size() 函数返回一个 tuple 的大小:
int n=tuple_size < tuple < int, string > >::value; // 2
tuple_element() 函数检索单个元素的类型。这个函数接收一个索引和 tuple 类型:
// get thefirst element's type, i.e., float
T=tuple_element < 0, tuple < float, int, char > >::type;
要访问元素本身,请使用 get() 函数模板。模板参数(也就是尖括号中括起来的参数)是元素的索引,圆括号中的参数是tuple类型:
tuple <int, double> tpl;
int n=get <0> (tpl); //read 1st element
get <1> (t)=9.5; //assign the 2nd element
3、应用
tuple 可以用来封装一个函数的多个返回值。例如:
typedeftuple < const char *, wchar_t* > mychar_t;
mychar_tmygetenv(const mychar_t &);
(Danny Kalev发表于2004-12-27 16:11:06)
C++ 标准委员会正在进行标准库(Standard Library)的扩展工作。这个扩展包括一个新的tuple库。下面我将讨论这个库和它的应用。(目前标准库文件中还没有包含这个库,所以你需要从 Boost 下载它的源文件:http://sourceforge.net/project/showfiles.php?group_id=7586
1、何为 tuple?
Tuple 是一个大小固定的异构对象集合。Tuple 类型有很多有用的应用,比如封装一个函数的多个返回值以及模拟多个对象的同时赋值和比较。
Tuple 的大小是指它所包含的元素的个数。目前的 tuple 库支持 0-10 个元素的 tuple。每个元素可以是不同的类型。下面的例子创建一个具有两个元素(分别为 float 和 void *)和一个匹配初始化例程的 tuple。
#include <tuple>
tuple <float, void *> t(2.5, NULL);
如果忽略初始化例程,会使用默认的初始化过程:
tuple <double, string> t; //initialized to (0.0, string())
2、辅助函数
Tuple 库包括几个辅助函数,例如,make_tuple() 函数根据其参数实例化一个tuple类型:
voidfunc(int n);
make_tuple(func); // returns: tuple < void (*)(int) >
make_tuple("test", 9); // tuple < const char (&)[5], int >
tuple_size() 函数返回一个 tuple 的大小:
int n=tuple_size < tuple < int, string > >::value; // 2
tuple_element() 函数检索单个元素的类型。这个函数接收一个索引和 tuple 类型:
// get thefirst element's type, i.e., float
T=tuple_element < 0, tuple < float, int, char > >::type;
要访问元素本身,请使用 get() 函数模板。模板参数(也就是尖括号中括起来的参数)是元素的索引,圆括号中的参数是tuple类型:
tuple <int, double> tpl;
int n=get <0> (tpl); //read 1st element
get <1> (t)=9.5; //assign the 2nd element
3、应用
tuple 可以用来封装一个函数的多个返回值。例如:
typedeftuple < const char *, wchar_t* > mychar_t;
mychar_tmygetenv(const mychar_t &);