Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/container/array/tuple element"

From cppreference.com
< cpp‎ | container‎ | array
m
m
Line 44: Line 44:
 
   typedef std::tuple_element<0, decltype(data)>::type zero_arr_type;
 
   typedef std::tuple_element<0, decltype(data)>::type zero_arr_type;
  
   // define compiler time constant tuple and get the types of the elements at positions 0 and 1
+
   // define compile time constant tuple and get the types of the elements at positions 0 and 1
 
   constexpr std::tuple<int, double> tup {10, 3.141592};
 
   constexpr std::tuple<int, double> tup {10, 3.141592};
 
   typedef std::tuple_element<0, decltype(tup)>::type zero_tup_type;
 
   typedef std::tuple_element<0, decltype(tup)>::type zero_tup_type;

Revision as of 11:17, 6 October 2017

 
 
 
 
Defined in header <array>
template< std::size_t I, class T, std::size_t N >
struct tuple_element<I, array<T, N> >;
(since C++11)

Provides compile-time indexed access to the type of the elements of the array using tuple-like interface

Contents

Member types

Member type Definition
type the type of elements of the array

Possible implementation

template<std::size_t I, class T>
  struct tuple_element;
 
template<std::size_t I, class T, std::size_t N>
  struct tuple_element<I, std::array<T,N> >
  {
     using type = T;
  };

Example

#include <array>
#include <iostream>
#include <tuple>
#include <type_traits>
 
int main()
{
   // define compile time constant array and get the type of the element at position 0
   constexpr std::array<int, 10> data {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
   typedef std::tuple_element<0, decltype(data)>::type zero_arr_type;
 
   // define compile time constant tuple and get the types of the elements at positions 0 and 1
   constexpr std::tuple<int, double> tup {10, 3.141592};
   typedef std::tuple_element<0, decltype(tup)>::type zero_tup_type;
   typedef std::tuple_element<1, decltype(tup)>::type one_tup_type;
 
   std::cout << std::boolalpha;
 
   // whether the type is constructed from a std::array or not, generated types are equivalent
   std::cout << std::is_same<zero_arr_type, zero_tup_type>::value << std::endl;
 
   // comparing int type to double type, expected to be false
   std::cout << std::is_same<zero_arr_type, one_tup_type>::value << std::endl;
 
   // in order to compare type directly to an int we must decay the generated type
   std::cout << std::is_same<std::decay<zero_tup_type>::type, int>::value << std::endl;
 
   // generated type is not exactly an int type!
   std::cout << std::is_same<zero_tup_type, int>::value << std::endl;
}

Output:

true
false
true
false

See also

obtains the type of the specified element
(class template specialization) [edit]
obtains the type of the elements of pair
(class template specialization) [edit]