Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to deduce a type of a single element of an array in c++

I'm having problem with deducing a type of a single element of an c++ array.

I would like to do achieve something like:

template <class T>
struct array_element { };

template <class T>
struct array_element<T[]> {
   using type = T;
};

int main() {
   int a[5] = {1, 2, 3, 4, 5};
   array_element<decltype(a)>::type element = a[0];
}

But the code obviously does not compile (the int[5] does not match T[])...

like image 989
W.F. Avatar asked May 24 '16 11:05

W.F.


People also ask

How do I find a single element in an array?

If you need the index of the found element in the array, use findIndex() . If you need to find the index of a value, use indexOf() .

How do you find unique elements in an array using XOR?

The way to find the unique element is by using the XOR bitwise operator which returns 1 only if one of the element is 1 and false otherwise. In the loop, each of the integers in the array are XORed with uniqueId starting at 0. Then, 0 is XOR'ed with 34.

Can an array have one element?

An array with a size of 1 can hold exactly one element at index 0.

Is used to identify the each element of an array?

Element − Each item stored in an array is called an element. Index − Each location of an element in an array has a numerical index, which is used to identify the element.


2 Answers

You need an extra argument for the specialization:

template <class T, size_t N>
struct array_element<T[N]> {
   using type = T;
};

Alternatively:

std::remove_reference<decltype(a[0])>::type element = a[0];

Or:

auto element = a[0];
like image 199
Maxim Egorushkin Avatar answered Oct 17 '22 07:10

Maxim Egorushkin


Use std::remove_extent template class (C++11) or std::remove_extent_t alias template (C++14) to get a type of an array element (both are declared in type_traits header file):

std::remove_extent<decltype(a)>::type element0 = a[0];

std::remove_extent_t<decltype(a)> element1 = a[1];

Live demo

You can also use std::remove_all_extents (C++11) or std::remove_all_extents_t (C++14) to get a type of an element of a multidimensional array.

like image 41
Constructor Avatar answered Oct 17 '22 06:10

Constructor