【发布时间】:2013-06-18 12:18:58
【问题描述】:
我知道有更简单的方法可以做到这一点,但是 我想在编译时初始化 从二维数组的展开索引到其一般格式的映射。
我想这样做而不需要实例化数组对象。
下面我从array[][]->array[] 定义地图。
现在我想知道如何做相反的事情:[] -> [][]
无需对所选映射方案进行硬编码。
我想这应该可以使用元编程和可变参数模板来实现。 但是几天前我第一次尝试使用它, 所以需要一段时间来适应;)
标题:
template <int dim>
class internal {
static unsigned int table[dim][dim];
static unsigned int x_comp[dim*dim];
static unsigned int y_comp[dim*dim];
};
来源:
//1d case:
template <>
unsigned int
internal<1>::table[1][1] = {{0}};
template <>
unsigned int
internal<1>::x_component[1] = {0};
template <>
unsigned int
internal<1>::y_component[1] = {0};
//2d case:
template<>
unsigned int
internal<2>::table[2][2] =
{{0, 1},
{2, 3}
};
// here goes some metaprogramming tricks to initialize
// internal<2>::y_component[2*2] = ...
// internal<2>::x_component[2*2] = ...
// based on mapping above, i.e. table[2][2];
// that is:
// x_table = { 0, 0, 1, 1 }
// y_table = { 0, 1, 0, 1 }
//
// so that :
//
// index == table[i][j]
// i == x_comp[index]
// j == y_comp[index]
EDIT1:
或者只是告诉我这是不可能的,我对所有内容都进行了硬编码或使用 整数除法以关联两个索引表示。
EDIT2: 我宁愿坚持任意数组的定义。 当然可以不用,如下面的答案中使用整数除法。
这些数组可以是任意的,例如:
template<>
unsigned int
internal<2>::table[2][2] =
{{3, 0},
{2, 1}
};
【问题讨论】:
-
您希望在
internal<2>::x_component等中包含哪些值? -
@ArneMertz 我在最后修改了问题以使其清楚
-
你能像
std::array和constexpr一样使用C++11的特性吗?如果您只想拥有这些索引,则不需要整个数组。 -
@ArneMertz std::array 和 constexpr 很好。我确实在其他地方使用 constexpr
标签: c++ templates metaprogramming template-meta-programming