c++ - 如何在编译时初始化静态二维数组

标签 c++ c++17 variadic-templates template-meta-programming

我做了一个数学上的多维数据结构,考虑下面的代码:

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/

相关文章:

c++ - 我找不到 g_io_channel_win32_make_pollfd 的任何文档

c++ - 并发状态文件处理具有多个过程,超出了我们对Linux和Windows的控制范围

c++ - 如何在 Qt 的另一个类中发出信号?

c++ - std::is_trivially_xxx 其中一个暗示另一个

c++ - 数值常量作为容器中的类型或变量?

c++ - 如何使用可变模板解决这个问题

c++ - cout对象的streambuf是如何初始化的?

c++ - 带有 stdenable_if 的嵌套名称说明符中使用的不完整类型

c++ - 使用可变参数模板从 Lua 函数回调 (C api) 中提取参数

c++ - 如何在可变模板的情况下应用模板模板参数