【问题标题】:can i initialize const instance so that i can use it as const to initialize array? [duplicate]我可以初始化 const 实例以便我可以将它用作 const 来初始化数组吗? [复制]
【发布时间】:2020-09-17 20:26:58
【问题描述】:

(小参考):

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);

但这并没有。

【问题讨论】:

  • std::array 的大小应该在编译时可用,但在您的示例中,它不是。如果您需要具有运行时动态大小的容器,请使用std::vector 而不是std::array。
  • 我想你可以用literal classes
  • 你只需要使用constexpr:godbolt.org/z/HdqYvN

标签: c++ arrays initialization constants


【解决方案1】:

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

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

【讨论】:

  • 问题是 floors 是一个类成员,编译器对该解决方案有问题。
  • 试试这样的class I{ static constexpr IVector2&lt;int&gt; floors = {10,1}; std::vector&lt;std::array&lt;int, floors.x - floors.y&gt;&gt; requestQueue; }; 现在它在另一个类中
猜你喜欢
  • 2010-09-29
  • 1970-01-01
  • 2021-11-18
  • 2011-02-15
  • 2014-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多