如何在c ++中复制Delphi的索引属性?

Joh*_*ica 3 c++ delphi properties

我希望能够在Delphi中使用以下构造,以便在c ++中工作

首先是Delphi代码:

type
  TSlice = record
  private
    function GetData4: UINT32; inline;
    procedure SetData4(Index: 0..15; Value: UINT32); inline;
  public
    Data8: array[0..7] of UINT64;
    property Data4[index: 0..15]: UINT32 read GetData4 write SetData4;
  end;
Run Code Online (Sandbox Code Playgroud)

现在我拥有并运行的c ++代码:

struct TSlice {
    UINT64 Data8[8];

    __device__ __forceinline__ UINT32 * Data4() { return reinterpret_cast<UINT32*>(Data8); }
}
Run Code Online (Sandbox Code Playgroud)

但是,我还是要写

for (auto i = 0; i < 3; i++) {
    Slice->Data4()[lane * 4] = SliverPart;
    Slice->Data4()[lane * 4 + 1] = SliverPart;
}
Run Code Online (Sandbox Code Playgroud)

我真的想放弃()这里:Slice->Data2[lane * 4]

声明Data4UINT32 *const Data4 = (UINT32 *)&Data8;
在结构中没有帮助,因为这给我增加了8个字节,这不是我想要的.
我希望翻译是无缝的.

我怎样才能做到这一点?

我正在考虑重载[]运算符,但这需要创建Data4一个子结构,即使这样我也不确定它是否会工作如果我想让所有内联工作(即没有任何运行时开销).

使用联合工作,但我需要在客户端代码中键入的点数超出这个世界(classname.unionname.datamember.arrayname[index])

Rem*_*eau 6

如果且仅当您使用C++ Builder时,您可以使用它的__property扩展,这是Delphi的直接等效property,例如:

struct TSlice
{
private:
    UINT32 GetData4(int Index);
    void SetData4(int Index, UINT32 Value);

public:
    UINT64 Data8[8];
    __property UINT32 Data4[int Index] = {read=GetData4, write=SetData4};
};
Run Code Online (Sandbox Code Playgroud)

在其他C++编译器,这不是直接可行的,但你可以得到接近使用一些辅助代理:如:

struct TSlice
{
private:
    UINT32 GetData4(int Index);
    void SetData4(int Index, UINT32 Value);

public:
    UINT64 Data8[8];

    TSlice() : Data4(*this) {}

    struct proxy
    {
    private:
        TSlice &m_slice;
        int m_index;

    public:
        proxy(TSlice &slice, int index) : m_slice(slice), m_index(index) {}

        operator UINT32() { return m_slice.GetData4(m_index); }
        proxy& operator=(UINT32 value) { m_slice.SetData4(m_index, value); return *this; }
    };

    struct property
    {
    private:
        TSlice &m_slice;

    public:
        property(TSlice &slice) : m_slice(slice) {}
        proxy operator[](int Index) { return proxy(m_slice, index); }
    };

    property Data4;
};
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用匿名联盟:

struct TSlice 
{
    union {
        UINT64 Data8[8];
        UINT32 Data4[16];
    };
};
Run Code Online (Sandbox Code Playgroud)