为什么std :: iS_array返回false for sTD ::数组

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

本文关键字:false for sTD 返回 数组 array std iS 为什么      更新时间:2023-10-16

,因为std::array<>std::is_array<>都在C 11中引入,因此这似乎很奇怪,因此无法编译:

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

是否有一种简单的方法来检查某物是否是数组,包括T[N]std::array<T,N>的可能性?

std::is_array仅适用于看起来像 T[]T[N]的类型。std::array不包括。

您不能在标准下修改std::is_array的CC_9为std::array;这将使您的程序不正确,无需诊断。当std中专门使用类型时,结果必须与标准一致,并且标准在此处是特定的。(此外,对于std中的其他模板,这样做对非法质疑)。

您可以创建自己的is_array特征:

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>{};
}

然后使用其他位置的notstd::is_array<T>检测C型数组或C std::array

iso/iec 14882:2011,§20.9.4.1,表47说:

  • 模板:模板struct is_array;

  • 条件:T是已知或未知范围的数组类型(3.9.2)

  • 评论:类模板数组(23.3.2)不是数组类型。

所以,断言应该失败。

尽管您可以按照 @0x499602d2提出的is_array进行专业化,但是如果您这样做,则应该在另一个名称空间中这样做,因为您不应该尝试更改标准化功能的含义。

cppReference提供了此可能的实现:

template<class T>
struct is_array : std::false_type {};
template<class T>
struct is_array<T[]> : std::true_type {};
template<class T, std::size_t N>
struct is_array<T[N]> : std::true_type {};

不幸的是,它没有为std::array提供专业化。您可以这样做:

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 {};