auto const a = make_point_2d(-1, 1);
a(2,0);
// 1. Why do I need the second index to access the elements of a Point2D?
// 2. Why can I access the element at index 2?
Which works, but is this the best way? Is there a better way to achieve what I want?
The best way depends on how you intend to use your Point2D.
If you really want Point2D and Matrix<3,1> to be the same, a possible approach is to make Point2D a type alias and write a make function to create it:
using Point2D = Matrix<3, 1>;
Point2D make_point_2d(float x, float y) { return Point2D{x, y, 1}; }
int main() {
auto const a = make_point_2d(-1, 1);
Matrix<3, 3> translate = {1, 0, 2, 0, 1, -2, 0, 0, 1};
Point2D out = translate * a;
}
To keep the design consistent, I'd introduce type aliases and make_* functions for other types too. E.g.:
This may work as long as the type aliases you need to introduce are not too many.
Edit: I'm not really sure having Point2D be (or publicly inherit from) Matrix<3,1> is a good idea. As a user, I'd be quite surprised by the fact this code would compile (and run without causing any assert to fail):
auto const a = make_point_2d(-1, 1);
a(2,0);
// 1. Why do I need the second index to access the elements of a Point2D?
// 2. Why can I access the element at index 2?
发布评论
评论(1)
最好的方法取决于您打算如何使用
Point2d
。如果您真的想要
point2d
和matrix&lt; 3,1&gt;
是相同的,那么一种可能的方法是制作point2d
类型别名并写入Make
函数来创建它:为了保持设计一致,我会介绍类型的别名和
Make _**
其他类型的功能。例如:只要您需要引入的类型别名并不多于太多,这可能会起作用。
编辑:我不确定
point2d
be(或公开继承)矩阵&lt; 3,1&gt;
是个好主意。作为用户,我会对这个事实感到惊讶此代码将编译(并且运行而不会导致任何
断言
失败):The best way depends on how you intend to use your
Point2D
.If you really want
Point2D
andMatrix<3,1>
to be the same, a possible approach is to makePoint2D
a type alias and write amake
function to create it:To keep the design consistent, I'd introduce type aliases and
make_*
functions for other types too. E.g.:This may work as long as the type aliases you need to introduce are not too many.
Edit: I'm not really sure having
Point2D
be (or publicly inherit from)Matrix<3,1>
is a good idea. As a user, I'd be quite surprised by the factthis code would compile (and run without causing any
assert
to fail):