简体   繁体   English

很好地初始化结构的联合

[英]Initializing union of structs nicely

I'm coding a Vec3 class, and for optimization purpose, I make it with no constructor. 我正在编码Vec3类,出于优化目的,我没有构造函数。 I also would like to be able to access its members as x, y, z OR as r, g, b OR as a tab. 我还希望能够以x,y,z或r,g,b或选项卡的形式访问其成员。 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 : 然后,由于我没有ctor,所以我想像这样初始化它:

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}} ) 但由于要在结构中初始化结构,因此必须加双括号(例如: 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) 我的尝试:每个组件具有一个并集,但随后将访问作为表退出(一个人总是可以调用&v.x并将其视为float [3],但这有点脏...而且不太安全,我猜测)

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): 如果您的编译器支持C ++ 11的此功能,则可以创建一个带有std::initializer_list的构造std::initializer_list (我知道您说过您不想拥有一个构造函数,但是此解决方案需要一个[但是我不需要如果您对[]进行优化,则认为它根本不会对性能造成影响,抱歉):

Vec3_t(std::initializer_list<T> list) : val(list) { }

Then you can construct a Vec3_t like you want: 然后,您可以根据需要构造一个Vec3_t

Vec3_t<int> v = {1, 2, 3};

没有构造函数就无法完成,并且避免不惜一切代价使用ctor是一个坏主意。

The closest you can get to initializing a class without a Ctor is use three predefined objects. 在没有Ctor的情况下初始化类最接近的方法是使用三个预定义的对象。 Each one initialized to one type of union you intend to use. 每个初始化为您要使用的一种联合类型。 Assign one of the desired kind to new object your are creating. 将一种所需的类型分配给要创建的新对象。

T t1;// array
T t2;// xyz
T t3;// rgb

T newT = t1;

That said, it is really difficult to imagine why you can not have Ctor, other than the reason you do not want it. 也就是说,除了您不想要Ctor的原因之外,很难想象您为什么不能拥有Ctor。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM