dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


advertisement
 

Tackle Common Programming Tasks Using the New <tuple> Library-2 : Page 2

Tuples are fixed size collections of heterogeneous objects, and they are being added to the C++ standard. Learn how this powerful facility can help you simplify several common programming tasks.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Construction and Initialization
A tuple type is a specialization, or an instance, of the class template tuple. The current library supports tuples with 0-10 elements. Each element may have a different type. In the following example, t is defined as a tuple type that contains two elements of type int and double:


#include <tuple>
tuple <int, double> t(1, 3.14);

For the sake of brevity, I do not use qualified names. The actual namespace in which tuple and its helper functions are declared depends on the library you're using. The Boost library declares them in boost::tuples. Standard C++ will declare them in std, as usual.



If you omit the initializers, default initialization will apply instead:


tuple <std::string, int*> u; //initialized to: string(),0

Helper Functions
To obtain a tuple's number of elements, use the tuple_size()function like this:


int sz=tuple_size < 
 tuple <int, const double, std::string> >::value;//3

The make_tuple()function facilitates the construction of tuple types. It creates a tuple type according to its arguments:


void f(int i);
T1=make_tuple(&f); // returns: tuple<void (*)(int)>
T2=make_tuple("hi", 2); // tuple< const char (&)[3], int>

tuple_element()returns the type of an individual element. This function takes an index and the tuple type:


//obtain the type of the first element
T=tuple_element <0, tuple<int, int, char> >::type;//int
>

If you need to access the actual element, not its type, use the get<N>()function. Note that tuples use zero-based indexing:


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


Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date