C++/CLI 指向成员的指针
在 C++/CLI 中实现指向成员的指针构造有哪些不同的选项?
我已经实现了一些 2D 几何算法,它们根据 X 和 Y 坐标执行一些操作。 我发现我经常为 X 轴复制一次代码,为 Y 轴复制一次代码。 一个示例是查找沿每个轴的最大和最小边界。
如果我使用本机 C++,我可以使用指向 X 或 Y 成员(还有宽度、高度等)的指针并将其作为参数传递,这样我只需实现每个算法一次。 但对于 C++/CLI,这是不可能的。 我有什么选择? 我正在寻找高效、轻量且简洁的东西。
What are the various options to implement a pointer-to-member construct in C++/CLI?
I have implemented some 2D geometry algorithms which perform some actions based on X and Y co-ordinates. I find that I am frequently duplicating code once for the X-axis and once for the Y-axis. An example is finding the maximum and minimum bounds along each axis.
Had I been using native C++, I could have used a pointer to the X or Y member (also width, height and so on) and passed it in as a parameter so that I need implement each algorithm only once. But with C++/CLI, this is not possible. What are my options? I am looking for something efficient, light-weight and terse.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会将参数设为模板类型参数,并使用封装属性访问的函子。 例如:
当然,只有当您有足够多足够长的算法来证明所有样板文件的合理性时,这才有意义。 尽管包装器可以通过宏生成和引用,但可以大大减少代码行数。
I'd make the argument a template type argument instead, and use functors that encapsulate property access. E.g.:
Of course, this only makes sense if you have sufficiently many sufficiently lengthy algorithms to justify all the boilerplate. Though the wrappers could be both generated and referenced via a macro, cutting down on lines of code quite a bit.
选项 1:如果 X 和 Y 公开为公共成员,您可以将它们定义为匿名联合的一部分,例如:
这允许您以 shape.X 或 shape.point[0] 的形式访问 X,类似地,以 shape.Y 的形式访问 X作为形状.点[1]。
选项 2:如果 X 和 Y 作为属性公开,您可以让它们的 getter/setter 访问两个元素的成员数组,然后将该数组也公开为只读属性。 虽然调用者无法修改数组属性,但仍然可以修改其元素。
选项3:好吧,这不是一个选项,真的。 不要使用 .NET 反射按名称访问属性。 运行时成本太高了。
Option 1: if X and Y are exposed as public members, you could define them as part of an anonymous union, e.g:
This lets you access X as either shape.X or shape.point[0], and similarly, shape.Y as shape.point[1].
Option 2: If X and Y are exposed as properties, you could have their getters/setters access a member array of two elements, and then expose the array as a read-only property too. While the caller can't modify the array property, it can still modify its elements.
Option 3: well, not an option, really. Don't use .NET reflection to access the properties by name. The runtime cost is way too high.