C++ equivalent of algebraic datatype?

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

    To throw another possibility in here, you can also use boost::variant which is being added to the standard library in C++17 as std::variant:

    struct Ball { float radius; };
    struct ConvexPolygon { Triangle t; }
    
    using Shape = boost::variant;
    

    The advantages of this approach:

    • Type-safe, unlike tagged unions
    • Can hold complex types, unlike unions
    • Does not require a uniform interface across all "child" types, unlike OO

    Some disadvantages:

    • Sometimes requires you to do a type check when accessing the variable to confirm that it is the type you want it to be, unlike OO
    • Requires you to use boost, or be C++17 compatible; these may be difficult with some compilers or some organizations where OO and unions are universally supported

提交回复
热议问题