我正在编写一个 Point
类(在 3d 空间中)并且一直想知道创建原点的最佳方法是什么。这是基本类(取自 Andy 的示例,以防万一有人想知道基本实现是什么):
struct Point
{
constexpr Point(double x_, double y_, double z_) : x(x_), y(y_), z(z_) { }
double x;
double y;
double z;
};
获得原点的第一种方法是定义一个 constexpr
变量:
constexpr Point origin = { 0.0, 0.0, 0.0 };
第二个是定义一个新类型和重载算法,如果它们在使用原点计算时可以从优化中受益(假设我为 Point
编写了一个 constexpr
构造函数) :
struct Origin: public Point
{
constexpr Origin():
Point(0.0, 0.0, 0.0)
{}
};
constexpr Origin origin;
虽然第一种方法看起来更简单且不易出错,但我想知道第二种方法是否是个好主意,它是否有一些我没有发现的缺陷。
编辑: 想到引用库,我注意到 CGAL 使用了类似的东西:
class Origin {};
const Origin ORIGIN;
最佳答案
While the first method seems simpler and less error-prone, I would like to know whether the second one looks like a good idea and whether it has some pitfalls I did not see.
我认为基于继承的设计在概念上是有缺陷的:你不想在这里引入一个新的类型,而起源在概念上是一个实例(一个非常特殊的实例,但仍然是一个实例) Point
类的,不是该类型的特化。
我宁愿在此处添加一个名为 origin()
的静态 constexpr
成员函数:
struct Point
{
constexpr Point(double x_, double y_, double z_) : x(x_), y(y_), z(z_) { }
constexpr static Point origin() { return {0, 0, 0}; }
double x;
double y;
double z;
};
然后你可以这样使用它:
int main()
{
constexpr Point o = Point::origin();
}
或者,您可以添加一个名为 origin
的 Point
类型的静态数据成员,而不是拥有一个名为 origin()
的静态函数。选择哪一个主要是品味问题。
关于c++ - 起源 - 不变的还是新的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16521458/