等效的static_asserts为is_array<>提供了冲突的结果

时间:2015-01-20 13:24:30

标签: c++ c++14 perfect-forwarding universal-reference forwarding-reference

在下面的代码片段中,静态断言通过而另一个失败:

template <class Rng> constexpr bool is_array(Rng&& r) {
  // int*** debug = r;  // uncomment this to debug r's type
  return std::is_array<Rng>{};
  // return std::is_array<decltype(r)>{};  // fails too
}

int a[5] = {0, 1, 2, 3, 4};
static_assert(std::is_array<decltype(a)>{}, ""); // passes
static_assert(is_array(a), ""); // fails

提示:删除注释以调试类型(它被正确推断为int [5])。

这是为什么?在铿锵行李箱上测试。

我猜它与衰变成指针的数组有关。不知何故。

解决方案:使用std::remove_reference_tRng将为int (&)[5],这是对数组的引用,而不是数组。

Xeo补充道:

template<class> struct dump;
dump<decltype(r)>{};

将无法编译并显示r的正确类型。

int**** j = r;产生了错误的错误(说不能int[5]int****投降。

1 个答案:

答案 0 :(得分:0)

Rng的类型是int (&)[5],它是对数组(而不是数组)的引用,因此std::is_array返回false_type

可以删除引用(例如使用std::remove_reference_t)以使其按预期工作。