Can I treat a struct like an array?

前端 未结 8 1647
野趣味
野趣味 2020-12-03 18:11

I have a struct for holding a 4D vector

struct {
    float x;
    float y;
    float z;
    float w;
} vector4f

And I\'m using a library th

8条回答
  •  天涯浪人
    2020-12-03 18:52

    If I had this situation, this is what I would do: C++ member variable aliases?

    In your case it would look like this:

    struct {
            float& x() { return values[0]; }
            float& y() { return values[1]; }
            float& z() { return values[2]; }
            float& w() { return values[3]; }
    
            float  operator [] (unsigned i) const { return this->values_[i]; }
            float& operator [] (unsigned i)       { return this->values_[i]; }
            operator float*() const { return this->values_; }
    
    private:
            float[4] values_;
    } vector4f;
    

    However, this doesn't address the question of treating a struct as an array if that's specifically what you wanted to know about.

提交回复
热议问题