【发布时间】:2018-05-09 23:12:27
【问题描述】:
假设我想编写一个结构体,它的成员 constexpr std::array 包含前 N 个 fib,其中 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 的解决方法,我会很高兴的。
【问题讨论】:
-
我想知道你为什么希望它是
std::array。此外,first_n_fibs<n>创建了很多实例,而所有这些(前缀)都相等。 -
因为IDK如何在编译时对C数组进行操作。至于实例和重复:我知道,但在某些情况下,这是值得的。
-
如果你在 C 数组上工作,那么任何前缀相等的 const
first_n_fibs都可以用指向最长数组的单个指针来表示。你能提供你的用例吗? -
否则,如果您只想在编译时获取
nth-fib,则std::array可能是矫枉过正。