相当于代数数据类型的C ++? [英] C++ equivalent of algebraic datatype?
问题描述
假设我有以下Haskell代码:
Let's say I have this Haskell code:
data RigidBody = RigidBody Vector3 Vector3 Float Shape -- position, velocity, mass and shape
data Shape = Ball Float -- radius
| ConvexPolygon [Triangle]
用C ++表示这一点的最佳方法是什么?
What would be the best way to express this in C++?
struct Rigid_body {
glm::vec3 position;
glm::vec3 velocity;
float mass;
*???* shape;
};
我要问的是,当结构可以是两种类型之一时,如何在结构中表示形状.
The thing I'm asking is how to represent shape inside the struct when it can be one of two types.
推荐答案
在C ++中可以使用多种方法来解决该问题.
There are different approaches that can be used to solve that problem in C++.
纯OO方法将定义一个接口Shape
,并具有两个不同的选项作为实现该接口的派生类型.然后,RigidBody
将包含指向Shape
的指针,该指针将被设置为引用Ball
或ConvexPolygon
.专业人士:人们喜欢OO(不确定这是否真的是专业人士:)),它很容易扩展(您以后可以添加更多形状而不更改类型).缺点:您应该为Shape
定义一个适当的接口,它需要动态分配内存.
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.
放在OO之外,可以使用boost::variant
或类似类型,它基本上是一个标记的联合,将容纳其中一种类型.优点:没有动态分配,形状是对象的局部.缺点:不是纯粹的OO(人们喜欢OO,您还记得吗?),扩展起来不太容易,不能一般地使用形状
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
这篇关于相当于代数数据类型的C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!