C++:非本地类型提升
假设我有一个 2D 矢量模板类:
template<typename T> class Vec2 {
T x, y;
// ...
};
我希望 Vec2
和 Vec2
之间的总和结果为a Vec2
,但 C++ 默认情况下不会这样做。
我的想法错了吗?
我应该尝试并实施这种行为吗?
我应该如何实施呢?一种方法可以是重载任何运算符,以便使用 auto
和 decltype
或某些 自己动手类型的提升,但这种方式绝非微不足道,甚至不允许我使用 boost.operators 来简化我的工作。其他建议?
Let's suppose I've got a 2D vector template class:
template<typename T> class Vec2 {
T x, y;
// ...
};
I'd expect that the result of a sum between a Vec2<double>
and a Vec2<int>
would be a Vec2<double>
, but C++ won't do this by default.
Am I thinking in the wrong way?
Should I try and implement this behavior?
And how would I be supposed to implement that? One way could be overloading any operator so that the promoted type is computed using auto
and decltype
or some do it yourself type promotion, but this way is anything but trivial and wouldn't even allow me to use boost.operators in order to ease my work. Other suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我确实喜欢这样:
http:// www.boost.org/doc/libs/1_43_0/doc/html/typeof/refe.html#typeof.typo
还有:
http://www.boost.org/doc/libs/1_46_0/libs/utility/operators.htm
I do like this:
http://www.boost.org/doc/libs/1_43_0/doc/html/typeof/refe.html#typeof.typo
also:
http://www.boost.org/doc/libs/1_46_0/libs/utility/operators.htm
Vec2
和Vec2
是完全独立的类型,恰好是从同一模板创建的。如果您希望任何涉及这两者的操作成为可能,您需要自己实现。您可以创建基于基本类型进行升级的通用运算符,或者您可以针对您需要的情况进行显式升级,这在 IMO 中更安全
Vec2<double>
andVec2<int>
are completely independent types that happened to be created from the same template. If you want any operation involving both of these to be possible, you need to implement it yourself.You can create generic operators that promote based on the base type, or you could make explicit promotions for the cases you need, which is IMO safer