std::tuple_element() and std::tuple_size() in C++ with Examples
A tuple is an object that can hold a number of elements. The elements can be different data types. The elements of tuples are initialized as arguments in the order in which they will be accessed.
The functions-
tuple_element() and tuple_size()
are only defined for elements using tuple_like interface.
tuple_element():
The C++ function tuple_element(array) provides compile-type indexed access to the type of the elements of the array using a tuple-like interface.
Syntax-
template< size_t I, class T, size_t N > struct tuple_element<I, array<T, N> >;
Parameters-
T − type for which the tuple element is obtained. I − index of the element. N − the size of the array.
Example-
Below is the C++ program to implement the concept of tuple_element(array)-
C++
// C++ program to implement // the above approach #include <array> #include <iostream> #include <tuple> #include <type_traits> using namespace std; // Driver code int main() { // Define array array< int , 3> data{ 3, 5, 10 }; // Type of element at index 0 using type = std::tuple_element<0, decltype (data)>::type; // Compare type with int // returns true cout << std::is_same<type, int >::value << '\n' ; // Compare type with char // returns false cout << std::is_same<type, char >::value << '\n' ; } |
1 0
tuple_size():
The C++ function tuple_size(array) returns the total number of elements present in the array.
Syntax-
template< class T, size_t N > class tuple_size< array<T, N> > : integral_constant<size_t, N> { };
Parameters-
T − type for which the tuple size is obtained.
Example-
Below is the C++ program to implement the concept of tuple_size()-
C++
// C++ program to implement // the above approach #include <array> #include <iostream> using namespace std; // Driver code int main() { // Array of size 6 array< int , 6> a; // Find size using tuple_size cout << tuple_size< decltype (a)>::value; return 0; } |
6
Please Login to comment...