我做了一个数学上的多维数据结构,考虑下面的代码:
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;
};
addIndices()
函数将两个组合索引分解为多维表示,然后将它们相加。
现在,我想创建一个大小为 [nElements][nElements]
的静态二维数组,它将替换函数 addIndices()
。我如何在编译时以优雅的方式做到这一点?
最佳答案
I want to create a static 2d array with size [nElements][nElements] that will replace the function "addIndices". How do I do that in an elegant way at compile time?
建议:避免使用 C 风格数组并使用(这次)std::array
。
根据这个建议,我提议
1) 使 getIndices()
成为一个 constexpr
方法
2) 定义以下using
(只是为了在以下几点简化您的生活)或类似的东西(也许有更好的名字)
using arr2D = std::array<std::array<std::size_t, nElements>, nElements>;
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)在类中添加如下static constexpr
成员(初始化如下)
static constexpr arr2D inds { getIndices() };
现在您的索引位于编译时初始化的 constexpr
成员中。
关于c++ - 如何在编译时初始化静态二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56245128/