【发布时间】:2021-02-07 18:00:25
【问题描述】:
鉴于std::array<T,N>::size 是 constexpr,在下面的 sn-p 中
- 为什么
Foo1::u不是static成员很重要?该类型在编译时是已知的,它的size()也是如此。 -
Foo2::bigger()有什么问题?
上市:
// x86-64 gcc 10.1
// -O3 --std=c++20 -pedantic -Wall -Werror
#include <array>
#include <cstdint>
union MyUnion {
std::array<uint8_t,32> bytes;
std::array<uint32_t,8> words;
};
struct Foo1 {
MyUnion u;
static constexpr size_t length {u.bytes.size()};
//invalid use of non-static data member 'Foo1::u'
};
struct Foo2 {
MyUnion u;
size_t x;
consteval int8_t length() const { return u.bytes.size(); };
bool bigger() const { return x > length(); }
//'this' is not a constant expression
};
我想在 MyUnion 声明中保留 std::array 长度,而不是诉诸
constexpr size_t LEN {32};
union MyUnion {
std::array<uint8_t,LEN> bytes;
std::array<uint32_t,LEN/4> words;
};
【问题讨论】:
-
请每个 stackoverflow.com 问题一个问题。这两个编译错误有不同的原因。
-
顺便说一下,如果你初始化了
bytes,你就不能使用words,因为它们没有共同的初始序列 -
想象一个静态函数因为您更改了一个非静态类成员而中断。这不好。
标签: c++ constexpr c++20 stdarray