C++ equivalent of algebraic datatype?

后端 未结 4 1321
花落未央
花落未央 2021-02-01 22:04

Let\'s say I have this Haskell code:

data RigidBody = RigidBody Vector3 Vector3 Float Shape -- position, velocity, mass an         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 22:33

    You are going to want to create a base class Shape. From here, you can create your actual shape classes, Ball and ConvexPolygon. You are going to want to make sure that Ball and ConvexPolygon are children of the base class.

    class Shape {
        // Whatever commonalities you have between the two shapes, could be none.
    };
    
    class Ball: public Shape {
        // Whatever you need in your Ball class
    };
    
    class ConvexPolygon: public Shape {
        // Whatever you need in your ConvexPolygon class
    };
    

    Now, you can make a generalized object like this

    struct Rigid_body {
        glm::vec3 position;
        glm::vec3 velocity;
        float mass;
        Shape *shape;
    };
    

    and when you actually initialize your shape variable, you can initialize it with either a Ball or ConvexPolygon class. You can continue making as many shapes as you would like.

提交回复
热议问题