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

标签 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;

现在我拥有并可以工作的 C++ 代码:

struct TSlice {
    UINT64 Data8[8];

    __device__ __forceinline__ UINT32 * Data4() { return reinterpret_cast<UINT32*>(Data8); }
}

不过,我还是要写

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

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

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

我该怎么做?

我正在考虑重载 [] 运算符,但这需要使 Data4 成为一个子结构,即使那样我也不确定它是否会起作用让一切都可以内联工作(即没有任何运行时开销)。

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

最佳答案

当且仅当,您正在使用 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};
};

在其他 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;
};

或者,您可以只使用匿名 union :

struct TSlice 
{
    union {
        UINT64 Data8[8];
        UINT32 Data4[16];
    };
};

关于c++ - 如何在 C++ 中复制 Delphi 的索引属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54404118/

相关文章:

delphi - 如何在Delphi2009+Vista中创建一个简单的听写板

javascript - 如何从 JavaScript 对象中删除属性?

php - 未定义的属性:Illuminate\Database\Eloquent\Collection::$id Laravel 4

java - Spring Boot多个同名同属性名的配置文件

Delphi - 使用 TIdMultipartFormDataStream idHTTP 上传文件

c++ - 如何在不重新建立堆不变量两次的情况下有效地替换堆顶元素?

c++ - 在 Windows Phone 8 C++ 中获取当前系统语言

c++ - 似乎无法在 C++ 中正确调用函数

c++ - Q : How to define a nondiscard boolean in C++17, 最好使用枚举?

sqlite - FireDac 未将 "&"符号插入 SQLITE varchar