首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >变量opIndex覆盖

变量opIndex覆盖
EN

Stack Overflow用户
提问于 2015-11-05 16:19:50
回答 1查看 106关注 0票数 1

按照我以前的question,我现在很难用不同的参数覆盖opIndex。我尝试过多种方法(甚至是黑客式的方法),但都没有效果。

用于生成标识符字符串的代码

代码语言:javascript
复制
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覆盖是什么样子的:

代码语言:javascript
复制
T opIndex(D...)(D indices)
{
    mixin("return " ~ array_decl("Data", indices) ~ ";");
}

在以下方面失败:

代码语言:javascript
复制
./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操作符。

我认为混合器是一种方法,因为我只需要生成一个格式为:

代码语言:javascript
复制
type[index0][index1]...[indexN] Data

用于opIndex过载。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-08 04:48:52

显然,这是不可能的,因为传递给opIndex的元组在编译时是不可访问的。我想出了几个解决方案(由Adam D. Ruppe提出的建议):

1. 硬编码阵列访问

使用编译时条件来索引数组,有点难看,可以访问的维度数量取决于实现条件的数量。

代码语言:javascript
复制
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. 指针

唯一的其他方法是将数组转换为指针,然后使用偏移量。计算偏移量,然后将其用于索引指针。

要能够在运行时访问模板参数,请执行以下操作:

代码语言:javascript
复制
struct Vector_MultiDim(T, D...)
{
    enum dimensions = [D];
    static const size_t DimCount = D.length;

    ... Other members here
}

函数计算偏移量(每个维度的大小必须在运行时知道):

代码语言:javascript
复制
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覆盖:

代码语言:javascript
复制
T opIndex(D...)(D indices)
{
    T* arr = cast(T*)Data;
    return arr[GetIndex([indices])];
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33549663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档