【问题标题】:Can't you just make a constexpr array by making a constexpr function that returns one?您不能通过创建一个返回一个的 constexpr 函数来创建一个 constexpr 数组吗?
【发布时间】:2022-01-15 22:36:27
【问题描述】:

我想在编译时构造一个数组值,并在网上看到多个来源建议使用带有 constexpr 构造函数的结构:

template<int N>
struct A {
    constexpr A() : arr() {
        for (auto i = 0; i != N; ++i)
            arr[i] = i; 
    }
    int arr[N];
};

int main() {
    constexpr auto a = A<4>();
    for (auto x : a.arr)
        std::cout << x << '\n';
}

这只是旧的建议(可能是 C++17 之前的建议?)还是我错过了什么,因为在我看来我可以做到以下几点:

constexpr std::array<int, 4> get_ary() {
    std::array<int, 4> ary = {};
    for (int i = 0; i < 4; ++i) {
        ary[i] = i;
    }
    return ary;
}

int main() {
    constexpr auto ary = get_ary();
    static_assert(ary.size() == 4, "The length should be 4!");
}

【问题讨论】:

    标签: c++ c++17 constexpr


    【解决方案1】:

    你不能通过创建一个返回 1 的 constexpr 函数来创建一个 constexpr 数组吗?

    不,你不能从一个函数中返回一个数组,不管它是不是 constexpr。

    但是,您可以返回包含数组作为成员的类的实例。您的A 是此类模板的一个示例,std::array 也是如此。这两个例子都是允许的。

    std::array 示例在 C++17 之前无法运行。返回没有问题,但使用非constexpr operator[]有问题。

    【讨论】:

    • 所以你可以返回一个 std::array 但你不能返回一个 C 风格的数组?
    • @jwezorek 是的,你可以返回类类型的实例,但你不能返回数组类型的实例。
    • @jwezorek - 这一直追溯到 C,它也可以返回结构,但不能返回 C 样式的数组。 C++ 无法轻易改变这一点。
    猜你喜欢
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多