按照我以前的question,我现在很难用不同的参数覆盖opIndex。我尝试过多种方法(甚至是黑客式的方法),但都没有效果。
用于生成标识符字符串的代码
static string array_decl(D...)(string identifier, D dimensions)
{
static if(dimensions.length == 0)
{
return identifier;
}
else
{
return array_decl(identifier ~ "[" ~ to!(string)(dimensions[0]) ~ "]", dimensions[1..$]);
}
}我的opIndex覆盖是什么样子的:
T opIndex(D...)(D indices)
{
mixin("return " ~ array_decl("Data", indices) ~ ";");
}在以下方面失败:
./inheritance.d(81): Error: tuple D is used as a type
./inheritance.d(89): Error: template instance inheritance.array_ident!(int, int, int).array_ident.array_ident!(_param_2, _param_3) error instantiating
./inheritance.d(112): instantiated from here: array_ident!(int, int, int)
./inheritance.d(174): instantiated from here: opIndex!(int, int, int)
./inheritance.d(112): Error: CTFE failed because of previous errors in array_ident
./inheritance.d(112): Error: argument to mixin must be a string, not ("return " ~ array_ident("Data", _param_0, _param_1, _param_2) ~ ";") of type string问题是在这种情况下如何(或有可能)实现opIndex操作符。
我认为混合器是一种方法,因为我只需要生成一个格式为:
type[index0][index1]...[indexN] Data用于opIndex过载。
发布于 2015-11-08 04:48:52
显然,这是不可能的,因为传递给opIndex的元组在编译时是不可访问的。我想出了几个解决方案(由Adam D. Ruppe提出的建议):
1. 硬编码阵列访问
使用编译时条件来索引数组,有点难看,可以访问的维度数量取决于实现条件的数量。
T opIndex(D...)(D indices)
{
static if(indices.length == 1)
{
return Data[indices[0]];
}
static if(indices.length == 2)
{
return Data[indices[0]][indices[1]];
}
static if(indices.length == 3)
{
return Data[indices[0]][indices[1]][indices[2]];
}
static if(indices.length == 4)
{
return Data[indices[0]][indices[1]][indices[2]][indices[3]];
}
}2. 指针
唯一的其他方法是将数组转换为指针,然后使用偏移量。计算偏移量,然后将其用于索引指针。
要能够在运行时访问模板参数,请执行以下操作:
struct Vector_MultiDim(T, D...)
{
enum dimensions = [D];
static const size_t DimCount = D.length;
... Other members here
}函数计算偏移量(每个维度的大小必须在运行时知道):
size_t GetIndex(size_t[] indices)
{
size_t index;
for(size_t i = 0; i < DimCount; i++)
{
size_t factor = 1;
for(size_t j = i + 1; j < DimCount; j++)
{
factor *= dimensions[j];
}
index += indices[i] * factor;
}
return index;
}opIndex覆盖:
T opIndex(D...)(D indices)
{
T* arr = cast(T*)Data;
return arr[GetIndex([indices])];
}https://stackoverflow.com/questions/33549663
复制相似问题