Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

c++ - How to cast one struct to another type with identical members?

If I'm given a struct variable like:

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

But I need to call a function expecting a

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

Is there a way in C++ to cast a variable of type Quaternion to type Vector?

question from:https://stackoverflow.com/questions/65670851/how-to-cast-one-struct-to-another-type-with-identical-members

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can write a converting constructor:

struct Quaternion {
    float    x;
    float    y;
    float    z;
    float    w;
    explicit Quaternion(const Vector& vec) : x(vec.x),y(vec.y),z(vec.z),w(vec.w) {}    
}

And similar for the other way.

In case you are looking for a way that does not require to copy the members, then I am not aware of a portable way to do that, and members having the same name does not help for that.

On the other hand, having same named members helps to write generic code like this:

 template <typename T>
 void foo(const T& t) {
     std::cout << t.x << t.y << t.z << t.w;
 }

You can call this with either a Quaternion or a Vector without needing to convert between them.

In case you cannot modify any existing code (not the structs nor the function you want to call), you can write a simple function to do the conversion (as suggested by ShadowRanger in a comment):

Vector Quat2Vect(const Quaternion& q) {
    return {q.x,q.y,q.z,q.w};
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...