您的位置:首页 > 移动开发

Examining the library and its applications

2004-09-23 16:01 323 查看
Examining the <tuple> library and its applications

Notice to subscribers: The final delivery of the C++ newsletter is Wednesday, Sept. 29, 2004. For more great coverage of development topics, subscribe to our other Builder.com newsletter offerings, including .NET and Web Development Zone.

The C++ standards committee is working on extending the Standard Library. The extensions include a new tuple library. I'll discuss this library and its applications. (This library isn't included in your Standard Library files yet; you'll need to download the source files from Boost.)

What's in a tuple?

A tuple is a fixed-size heterogeneous collection of objects. Tuple types have many useful applications, such as packing multiple return values of a function and imitating simultaneous assignment of multiple objects.

A tuple's size is the number of elements it contains. The current tuple library supports tuples with 0-10 elements. Each element may be of a different type. The following example creates a tuple type that has two elements, float and void *, and matching initializers:

#include <tuple>
tuple <float, void *> t(2.5, NULL);

If you omit the initializers, default initialization will take place instead:

tuple <double, string> t; //initialized to (0.0, string())

Helper functions

The tuple library includes several helper functions. For instance, make_tuple() instantiates a tuple type according to its arguments:

void func(int n);
make_tuple(func); // returns: tuple < void (*)(int) >
make_tuple("test", 9); // tuple < const char (&)[5], int >

The tuple_size() function returns a tuple's size:

int n=tuple_size < tuple < int, string > >::value; // 2

The tuple_element() function retrieves an individual element's type. This function takes an index and the tuple type:

// get thefirst element's type, i.e., float
T=tuple_element < 0, tuple < float, int, char > >::type;

To access the element itself, use the get() function template. The template argument (i.e., the argument passed in the angular brackets) is the element's index, and the argument in parentheses is the tuple type:

tuple <int, double> tpl;
int n=get <0> (tpl); //read 1st element
get <1> (t)=9.5; //assign the 2nd element

Applications

You can use a tuple to pack multiple return values of a single function. For example:

typedef tuple < const char *, wchar_t* > mychar_t;
mychar_t mygetenv(const mychar_t &);

Danny Kalev is a systems analyst and software engineer with 14 years of experience, specializing in C++ and object-oriented design.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐