C++ equivalent of algebraic datatype?

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

    There are different approaches that can be used to solve that problem in C++.

    The pure-OO approach you would define an interface Shape and have the two different options as derived types implementing that interface. Then the RigidBody would contain a pointer to a Shape that would be set to refer to either a Ball or a ConvexPolygon. Pro: people love OO (not sure this is a pro really :)), it is easily extensible (you can add more shapes later on without changing the type). Con: You should define a proper interface for Shape, it requires dynamic allocation of memory.

    Putting OO aside, you can use a boost::variant or similar type, that is basically a tagged union that will hold one of the types. Pro: no dynamic allocations, shape is local to the object. Con: not pure-OO (people love OO, you remember right?), not so easy to extend, cannot use the shape generically

提交回复
热议问题