为什么std :: iS_array返回false for sTD ::数组
Why does std::is_array return false for std::array?
,因为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 {};
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- "error: no matching function for call to"构造函数错误
- 表示"accepting anything for this template argument" C++概念的通配符
- 如何在C++中从两个单独的for循环中添加两个数组
- 伪造事实↔false
- QueryWorkingSet总是返回false
- 在Linux for Windows上编译C++代码时出错
- 调用专用模板时出错"no matching function for call to [...]"
- 为什么我的for循环不能正确获取argv
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 如果任何条件是错误的,如何从for循环中返回false
- setData returns false for QAbstractProxyModel
- 为什么std :: iS_array返回false for sTD ::数组
- regex_search() return false for positive lookbehind and look
- 如何使用基于范围的 for 循环将 2D 数组初始化为 false
- 如何在布尔值(false和true)上编写“for”循环