Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::is_array return false for std::array?

Since std::array<> and std::is_array<> were both introduced in C++11, it seems very strange that this fails to compile:

#include <array>
#include <type_traits>

static_assert(std::is_array<std::array<int,2>>::value);

Is there a simple way to check if something is an array, including both the possibilities of T[N] and std::array<T,N>?

like image 609
John Zwinck Avatar asked Dec 02 '16 03:12

John Zwinck


1 Answers

std::is_array is defined to be true only for types that look like T[] or T[N]. std::array is not included.

You cannot modify or specialize std::is_array to be true_type for std::array under the standard; that would make your program ill-formed, no diagnostic required. When specializing types within std, the result must be consistent with the standard, and the standard is specific here. (Also, doing so for other templates within std is highly questionable to illegal).

You can create your own is_array trait:

namespace notstd {
  template<class T>
  struct is_array:std::is_array<T>{};
  template<class T, std::size_t N>
  struct is_array<std::array<T,N>>:std::true_type{};
  // optional:
  template<class T>
  struct is_array<T const>:is_array<T>{};
  template<class T>
  struct is_array<T volatile>:is_array<T>{};
  template<class T>
  struct is_array<T volatile const>:is_array<T>{};
}

then use notstd::is_array<T> elsewhere to detect either C-style arrays or C++ std::array.

like image 151
Yakk - Adam Nevraumont Avatar answered Oct 11 '22 21:10

Yakk - Adam Nevraumont