很好地初始化结构体的联合
我正在编写一个 Vec3 类,为了优化目的,我没有使用构造函数。 我还希望能够以 x、y、z 或 r、g、b 或选项卡的形式访问其成员。 很简单,您可能会认为:使用联合
template <typename T> struct Vec3_t
{
union
{
T val[3];
struct { T x, y, z; };
struct { T r, g, b; };
};
};
然后,由于我没有构造函数,我想像这样初始化它:
Vec3_t<int> v = {1, 2, 3};
但是我必须放置双括号,因为我正在结构中初始化一个结构(如下所示:Vec3_t
)
所以,我的问题是:我怎样才能使用不同的名称进行访问,并用一对大括号初始化?
我的尝试:每个组件都有一个联合,但然后以表的形式退出(人们总是可以调用 &vx 并将其视为浮点[3],但这有点脏......而且不太安全我猜测)
I'm coding a Vec3 class, and for optimization purpose, I make it with no constructor.
I also would like to be able to access its members as x, y, z OR as r, g, b OR as a tab.
Easy, you might think : use a union
template <typename T> struct Vec3_t
{
union
{
T val[3];
struct { T x, y, z; };
struct { T r, g, b; };
};
};
Then, since I have no ctor, I would like to initialize it like this :
Vec3_t<int> v = {1, 2, 3};
but I have to put double braces since I'm initializing a struct in a struct (like this : Vec3_t<int> v = {{1, 2, 3}}
)
So, my question is : How could I do it so that I can have both access with different names, and initialization with one pair of braces ?
my try : having one union for each component, but then exit with the access as a table (one can always call &v.x and treat it as a float[3], but that's kind of dirty... and not so safe I guess)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的编译器支持 C++11 的此功能,您可以创建一个采用
std::initializer_list
的构造函数(我知道您说过您不想有构造函数,但此解决方案需要一个[但我认为如果您进行了优化,它根本不会影响性能],抱歉):然后您可以像您想要的那样构造一个
Vec3_t
:If your compiler supports this feature of C++11, you can create a constructor that takes an
std::initializer_list
(I know you said you didn't want to have a constructor, but this solution requires one [but I don't think it cause a performance hit at all if you have optimisations on], sorry):Then you can construct a
Vec3_t
like you want:没有构造函数就无法完成此操作,并且不惜一切代价避免使用构造函数是一个坏主意。
It cannot be done without a constructor, and it is a bad idea to avoid using a ctor at all costs.
与在没有 Ctor 的情况下初始化类最接近的方法是使用三个预定义对象。每个都初始化为您打算使用的一种类型的联合。将所需类型之一分配给您正在创建的新对象。
也就是说,除了你不想要 Ctor 的原因之外,真的很难想象为什么你不能拥有 Ctor。
The closest you can get to initializing a class without a Ctor is use three predefined objects. Each one initialized to one type of union you intend to use. Assign one of the desired kind to new object your are creating.
That said, it is really difficult to imagine why you can not have Ctor, other than the reason you do not want it.