现代C ++:初始化constexpr表 [英] Modern C++: initialize constexpr tables
问题描述
假设我有一个类 X
,该功能需要大量常量表值,例如数组 A [1024]
。我有一个递归函数 f
计算其值,类似
Suppose I have a class X
, which functionality requires a lot of constant table values, say an array A[1024]
. I have a recurrent function f
that computes its values, smth like
A[x] = f(A[x - 1]);
假设 A [0]
是一个已知常数,因此数组的其余部分也是常数。使用现代C ++的功能并且不使用此数组的硬编码值存储文件的情况下,预先计算这些值的最佳方法是什么?我的解决方法是const静态伪变量:
Suppose that A[0]
is a known constant, therefore the rest of the array is constant too. What is the best way to calculate these values beforehand, using features of modern C++, and without storaging file with hardcoded values of this array? My workaround was a const static dummy variable:
const bool X::dummy = X::SetupTables();
bool X::SetupTables() {
A[0] = 1;
for (size_t i = 1; i <= A.size(); ++i)
A[i] = f(A[i - 1]);
}
但是我相信,这并不是最美丽的方式。
注意:我强调数组很大,我想避免代码的怪异。
But I believe, it’s not the most beautiful way to go. Note: I emphasize that array is rather big and I want to avoid monstrosity of the code.
推荐答案
自C ++ 14起, for
循环就可以在 constexpr
函数。此外,自C ++ 17起, std :: array: :operator []
也是 constexpr
。
Since C++14, for
loops are allowed in constexpr
functions. Moreover, since C++17, std::array::operator[]
is constexpr
too.
因此,您可以写这样的东西:
So you can write something like this:
template<class T, size_t N, class F>
constexpr auto make_table(F func, T first)
{
std::array<T, N> a {first};
for (size_t i = 1; i < N; ++i)
{
a[i] = func(a[i - 1]);
}
return a;
}
示例: https://godbolt.org/g/irrfr2
这篇关于现代C ++:初始化constexpr表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!