gpt4 book ai didi

c++ - 是否可以以编程方式初始化 constexpr std::array 成员

转载 作者:搜寻专家 更新时间:2023-10-31 00:27:08 25 4
gpt4 key购买 nike

假设我想编写一个结构,它有一个包含前 N 个 fib 的成员 constexpr std::array,其中 N 是一个模板参数。

类似这样,但在编译时可以使用 vals:

template <int N>
struct first_n_fibs {
static_assert(N>0);
static const std::array<int, N> vals;
static std::array<int, N> init_fibs(){
std::array<int,N> result;
if (N==1) {
return std::array<int,N>{1};
} else {
result[0]=1;
result[1]=1;
for(int i =2; i<N;++i) {
result[i]=result[i-2]+result[i-1];
}
}
return result;
}
};

template<int N>
const std::array<int, N> first_n_fibs<N>::vals=init_fibs();


int main(){
std::cout << first_n_fibs<2>::vals.back() << std::endl;
std::cout << first_n_fibs<5>::vals.back() << std::endl;
std::cout << first_n_fibs<6>::vals.back() << std::endl;
}

我怀疑没有解决方法,因为 std::array 构造函数不是 constexpr,所以如果有人知道涉及 C 数组或 boost 的任何解决方法,我会很高兴。

最佳答案

你不需要任何特别的东西,constexpr 这些天函数要求非常宽松:

#include <iostream>
#include <array>

template <int N> constexpr std::array<int, N> first_n_fibs()
{
std::array<int, N> ret{};
ret[0] = 0;
if (N == 1) return ret;
ret[1] = 1;
for (int i = 2; i < N; i++)
ret[i] = ret[i-2] + ret[i-1];
return ret;
}

int main()
{
constexpr auto a = first_n_fibs<3>();
}

(try it live)


std::array constructors are not constexpr

显然它有 no user-defined constructors at all ,所以没有什么能阻止它的构造成为 constexpr

关于c++ - 是否可以以编程方式初始化 constexpr std::array 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50263306/

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