Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the type of an array element?

I can't get the type of an element. This solution returns a reference to element type.

int arr[] = { 0, 1, 2, 3, 4, 5 };
using arrElemType = decltype(*arr);
vector<arrElemType> vec(std::cbegin(arr), std::cend(arr));
like image 759
NuPagadi Avatar asked Mar 14 '14 16:03

NuPagadi


2 Answers

Try the following

using arrElemType = std::remove_reference<decltype( *arr )>::type;

or

typedef std::remove_reference<decltype( *arr )>::type arrElemType;

You need to include header <type_traits>

like image 178
Vlad from Moscow Avatar answered Sep 28 '22 16:09

Vlad from Moscow


The standard way in C++11 and above is to use std::remove_all_extents.

#include <type_traits>

int arr[] = { 0, 1, 2, 3, 4, 5 };
using arrElemType = std::remove_all_extents<decltype(arr)>::type;
vector<arrElemType> vec(std::cbegin(arr), std::cend(arr));
like image 43
Benjamin T Avatar answered Sep 28 '22 16:09

Benjamin T