std::tuple_size<std::tuple>

From cppreference.com
< cpp‎ | utility‎ | tuple
Defined in header <tuple>
template< class T >
class tuple_size; /*undefined*/
(1) (since C++11)
template< class... Types >

class tuple_size< std::tuple<Types...> >

 : public std::integral_constant<std::size_t, sizeof...(Types)> { };
(2) (since C++11)
Defined in header <tuple>
Defined in header <array>
Defined in header <utility>
(since C++17)
(since C++17)
template< class T >

class tuple_size<const T>

 : public std::integral_constant<std::size_t, tuple_size<T>::value> { };
(3) (since C++11)
template< class T >

class tuple_size< volatile T >

 : public std::integral_constant<std::size_t, tuple_size<T>::value> { };
(4) (since C++11)
template< class T >

class tuple_size< const volatile T >

 : public std::integral_constant<std::size_t, tuple_size<T>::value> { };
(5) (since C++11)

Provides access to the number of elements in a tuple as a compile-time constant expression.

In addition to being available via inclusion of the <tuple> header, the templates (3-5) are available when either of the headers <array> or <utility> are included.

All specializations of std::tuple_size satisfy UnaryTypeTrait with BaseCharacteristic std::integral_constant<std::size_t, N> for some N.

The cv-T templates (3-5) are SFINAE-friendly: if std::tuple_size<T>::value is ill-formed when treated as an unevaluated operand, (3-5) do not provide the member value. Access checking is performed as if in a context unrelated to tuple_size and T. Only the validity of the immediate context of the expression is considered.

(since C++17)

Helper variable template

template< class T >
inline constexpr std::size_t tuple_size_v = tuple_size<T>::value;
(since C++17)

Inherited from std::integral_constant

Member constants

value
[static]
sizeof...(Types)
(public static member constant)

Member functions

operator std::size_t
converts the object to std::size_t, returns value
(public member function)
operator()
(C++14)
returns value
(public member function)

Member types

Type Definition
value_type std::size_t
type std::integral_constant<std::size_t, value>

Example

#include <iostream>
#include <tuple>
 
template <class T>
void test(T t)
{
    int a[std::tuple_size<T>::value]; // can be used at compile time
 
    std::cout << std::tuple_size<T>::value << '\n'; // or at run time
}
 
int main()
{
    test(std::make_tuple(1, 2, 3.14));
}

Output:

3

See also

obtains the size of an array
(class template specialization)
obtains the size of a pair
(class template specialization)
tuple accesses specified element
(function template)
obtains the type of the specified element
(class template specialization)