[英]How to initialize static two dimensional array in compile-time
I made a mathematical multi-dimensional data structure, consider the following code: 我做了一个数学的多维数据结构,考虑下面的代码:
template <class T, size_t ... Dims>
class ZAMultiDimTable
{
public:
static constexpr size_t nDims = sizeof...(Dims);
static constexpr size_t nElements = (... * Dims);
static constexpr std::array<size_t, nDims> _indices = {Dims...};
static size_t addIndices(size_t ind1,size_t ind2)
{
size_t ret = 0;
size_t mul = 1;
for (size_t i=0; i< nDims;++i)
{
ret+=mul*((ind1+ind2)%_indices[i]);
ind1/=_indices[i];
ind2/=_indices[i];
mul*=_indices[i];
}
return ret;
}
friend inline const ZAMultiDimTable<T, Dims...> operator*(const ZAMultiDimTable<T, Dims...>& l,const ZAMultiDimTable<T, Dims...>& r)
{
ZAMultiDimTable<T, Dims...> m;
for(size_t i=0; i < nElements; ++i)
{
for (size_t j = 0; j < nElements; ++j)
{
m._table[addIndices(i,j)]+=l._table[i]*r._table[j];
}
}
return m;
}
private:
std::array<T, nElements > _table;
};
the function addIndices()
breaks two combined indices to the representation of multi-dimensions, and then add them. 函数
addIndices()
将两个组合索引分解为多维表示,然后将它们相加。
Now, I want to create a static 2d array with size [nElements][nElements]
that will replace the function addIndices()
. 现在,我想创建一个大小为
[nElements][nElements]
的静态2D数组,它将替换函数addIndices()
。 How do I do that in an elegant way at compile time? 在编译时如何以一种优雅的方式做到这一点?
I want to create a static 2d array with size [nElements][nElements] that will replace the function "addIndices".
我想创建一个大小为[nElements] [nElements]的静态2D数组,该数组将替换函数“ addIndices”。 How do I do that in an elegant way at compile time?
在编译时如何以一种优雅的方式做到这一点?
Suggestion: avoid C-style arrays and use (this time) std::array
instead. 建议:避免使用C样式的数组,而(这次)使用
std::array
代替。
Following this suggestion, I propose 根据这个建议,我建议
1) make getIndices()
a constexpr
method 1)使
getIndices()
为constexpr
方法
2) define the following using
(just to simplify your life in following points) or something similar (maybe with a better name) 2)定义以下
using
(只是为了简化以下几点你的生活)或类似的东西(也许有更好的名字)
using arr2D = std::array<std::array<std::size_t, nElements>, nElements>;
3) define the following static constexpr
method 3)定义以下
static constexpr
方法
static constexpr arr2D getIndices ()
{
arr2D ret;
for ( auto i = 0u ; i < nElements; ++i )
for ( auto j = 0u ; j < nElements; ++j )
ret[i][j] = addIndices(i, j);
return ret;
}
4) add the following static constexpr
member in the class (initialized as follows) 4)在类中添加以下
static constexpr
成员(初始化如下)
static constexpr arr2D inds { getIndices() };
Now you have your indices in a constexpr
member that is initialized compile-time. 现在,您将索引放在已初始化编译时的
constexpr
成员中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.