我很想知道为什么第二个 static_assert
在我下面的代码中不起作用。似乎即使数组 c
是对 a
的引用,数组的大小嵌入在类型中,因此它应该在编译时可用。
#include <array>
int main()
{
std::array<int,2> a = {1,2};
std::array<int,2> b = {2,3};
std::array<int,2>& c = a;
static_assert(a.size() == b.size(), "a.size==b.size"); // ok size of array is compile time constant
static_assert(c.size() == a.size(), "c.size==a.size"); // compiler error "static_assert expression is not an integral constant expression"
}
最佳答案
the size of the array is embedded in the type, so it should be available at compile time.
这是真的。但不管怎样,
c
不是常量表达式,因此包含它作为子表达式的表达式不能是常量表达式 - 除了某些仅与操作数类型交互的运算符,例如 sizeof
.例如,您可以使用以下方法获取尺寸:
static_assert(
std::tuple_size<
std::remove_reference_t<decltype(c)>
>::value == a.size(),
"c.size==a.size"
);
不幸的是,它不是很漂亮。
关于c++ - 编译时对 std::array 的引用大小不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63331579/