[英]Size of reference to std::array not available at compiletime
I'm interested to know why the second static_assert
in my code below doesn't work.我很想知道为什么下面代码中的第二个static_assert
不起作用。 It seems like even though the array c
is a reference to a
, the size of the array is embedded in the type, so it should be available at compile time.似乎即使数组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.数组的大小嵌入在类型中,因此它应该在编译时可用。
This is true.这是真实的。 But regardless, c
is not a constant expression and therefore expression that contains it as a subexpression cannot be a constant expression - except certain operators that interact only with the type of the operand such as sizeof
.但无论如何, c
不是常量表达式,因此包含它作为子表达式的表达式不能是常量表达式 - 除了某些仅与操作数类型交互的运算符,例如sizeof
。
You can get the size for example using:例如,您可以使用以下方法获取大小:
static_assert(
std::tuple_size<
std::remove_reference_t<decltype(c)>
>::value == a.size(),
"c.size==a.size"
);
Unfortunately, it is not very pretty.不幸的是,它不是很漂亮。
Note, that if you move all declaration out of main function, code would compile.请注意,如果您将所有声明移出主 function,代码将编译。 Why?为什么? Because a
is automatic variable, so it's not really a compile time object and reference is not elided here, therefore neither a
nor c
or c.size()
are constexpr
.因为a
是自动变量,所以它不是真正的编译时间 object 并且这里没有省略引用,因此a
和c
或c.size()
都不是constexpr
. For global variables location of a
can be determined at compile time.对于全局变量, a
位置可以在编译时确定。
IF you try bind them within function like this:如果您尝试将它们绑定在 function 中,如下所示:
constexpr std::array<int,2> a = {1,2};
std::array<int,2> b = {2,3};
constexpr const std::array<int,2>& c = a;
You'll get error that a
is not a constant expression.你会得到a
不是常量表达式的错误。 Variant which still may compile:仍然可以编译的变体:
#include <array>
std::array<int,2> a = {1,2};
std::array<int,2> b = {2,3};
int main()
{
std::array<int,2>& c = a;
static_assert(a.size() == b.size(), "a.size==b.size");
static_assert(c.size() == a.size(), "c.size==a.size");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.