我希望能够使 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/