gpt4 book ai didi

C++ - 有没有办法为字段创建别名

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:15:06 25 4
gpt4 key购买 nike

有没有办法为 C++11 中的类/结构创建别名?我的意思是

我上课了

class Vector4
{
public:
float X,Y,Z,W;
}

我有一个别名

typedef Vector4 Color;

有没有办法为 Vector4 X、Y、Z、W 字段创建别名以作为颜色 R、G、B、A 工作?

最佳答案

只需像这样定义 Vector4,使用匿名 union (没有匿名结构,尽管它们是常见的扩展)。

typedef struct Vector4
{
union{float X; float R;};
union{float Y; float G;};
union{float Z; float B;};
union{float W; float A;};
} Vector4;
typedef Vector4 Color;

如果您不能重新定义 Vector4,您可能只是定义一个布局兼容的标准布局类并使用可怕的 reinterpret_cast
这是可行的,因为具有布局兼容成员的标准布局类是兼容的。

struct Color
{
float R, G, B, A;
}

标准报价:

A standard-layout class is a class that:
— has no non-static data members of type non-standard-layout class (or array of such types) or reference,
— has no virtual functions (10.3) and no virtual base classes (10.1),
— has the same access control (Clause 11) for all non-static data members,
— has no non-standard-layout base classes,
— either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and
— has no base classes of the same type as the first non-static data member.

A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class.
A standard-layout union is a standard-layout class defined with the class-key union.

关于C++ - 有没有办法为字段创建别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23175323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com