我可以初始化 const 实例,以便我可以将其用作 const 来初始化数组吗?

can i initialize const instance so that i can use it as const to initialize array?

本文关键字:我可以 const 初始化 数组 实例      更新时间:2023-10-16

(小参考(:

template<typename T>
struct IVector2 {
T x, y;
IVector2(T x, T y) :
x(x), y(y) { }
};

有没有办法做到这一点:

static const IVector2<int> floors;  // lowest / highest floor
std::vector<std::array<IPerson, floors.x - floors.y>> requestQueue;

我需要初始化数组大小以使其在 floor.x 和 floor.y 之间有所不同。 我一直在寻找有关如何初始化楼层的答案,我得到了这个

const IVector2<int> IElevatorHandler::floors(-1, 4);

但这并不能做到这一点。

您可以尝试为此使用文字类。我对您的代码进行了一些更改

template<typename T>
struct IVector2 {
T x, y;
constexpr IVector2(T x, T y) : //constexpr constructor
x(x), y(y) { }
};

static constexpr IVector2<int> floors(10,1);  // Initialized constexpr object. Now available at compile time