Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

std::tuple_element() and std::tuple_size() in C++ with Examples

  • Last Updated : 10 Jul, 2021

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.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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';
}
Output
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;
}
Output
6



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!