gpt4 book ai didi

c++ - 获取 std::array 的 constexpr 初始化成员数

转载 作者:行者123 更新时间:2023-11-30 03:17:47 27 4
gpt4 key购买 nike

我在编译时用一个初始化列表初始化一个 std::array,我想有一种方法来存储元素的数量。 std::array::size()将返回整个数组的大小,这不是我要找的。

我怎样才能改进下面的代码?非常感谢!

#include <array>

constexpr std::array<int, 5> a{{1, 2, 3}};

constexpr size_t element_count(const std::array<int, 5> &a) { return ???; }

int main() { static_assert(element_count(a) == 3); }

我正在编译 g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0 .

最佳答案

在 C++14 中没有办法很好地做到这一点。数组的类型在其声明中是固定的,并且无论实际初始化为非零值的元素数量如何,它都保持不变。

在 C++17 中你会这样做

std::array arr{1, 2, 3, 4};

但在 C++14 中,您必须使用 auto 变量和 make_array 类型的函数。如果您愿意,我可以展示示例代码。

附言事实上,std::array 缺乏自动数组长度推导是我在我的一些代码中使用 C 风格数组的唯一原因。

关于c++ - 获取 std::array 的 constexpr 初始化成员数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55189993/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com