Suppose I have a type T which is guaranteed to be an array (eg. int[32]). How do I get the type of the elements from the type of the array?
If you use typeid().name()
, as in you example, you get the name of the type, not the type.
If you want the type, and use it compile time, and you want it to declare variables, you can define a type traits as follows
template <typename>
struct typeOfArray
{ };
template <typename T, std::size_t N>
struct typeOfArray<T[N]>
{ using type = T; };
The following is a full (but c++11) working example
#include <iostream>
#include <type_traits>
template <typename>
struct typeOfArray
{ };
template <typename T, std::size_t N>
struct typeOfArray<T[N]>
{ using type = T; };
int main ()
{
static_assert( std::is_same<int,
typename typeOfArray<int[1]>::type>::value, "!" );
static_assert( std::is_same<float,
typename typeOfArray<float[1]>::type>::value, "!" );
typename typeOfArray<int[1]>::type i { 42 };
std::cout << i << std::endl;
}
If you have to work with c++98, you can't use using
, so instead of
using type = T;
you have to use typedef
typedef T type;
The following is a c++98 example (using typeid().name()
also)
#include <typeinfo>
#include <iostream>
template <typename>
struct typeOfArray
{ };
template <typename T, std::size_t N>
struct typeOfArray<T[N]>
{ typedef T type; };
int main ()
{
std::cout << typeid(typeOfArray<int[1]>::type).name() << std::endl;
std::cout << typeid(typeOfArray<float[1]>::type).name() << std::endl;
}