C++ equivalent of algebraic datatype?

后端 未结 4 1322
花落未央
花落未央 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:34

    The canonical way to do this in C++ is the inheritance-based solution given in Justin Wood's answer. Canonically, you endow the Shape with virtual functions that each kind of Shape

    However, C++ also has union types. You can do "tagged unions" instead:

    struct Ball { /* ... */ };
    struct Square { /* ... */ };
    struct Shape {
      int tag;
      union {
        Ball b;
        Square s;
        /* ... */
      }
    };
    

    You use the tag member to say whether the Shape is a Ball or a Square or whatever else. You can switch on the tag member and whatnot.

    This has the disadvantage that a Shape is one int larger than the biggest of Ball and Square and the others; objects in OCaml and whatnot do not have this problem.

    Which technique you use will depend on how you're using the Shapes.

提交回复
热议问题