C++:非本地类型提升

发布于 2024-10-19 15:59:10 字数 566 浏览 5 评论 0原文

假设我有一个 2D 矢量模板类:

template<typename T> class Vec2 {
    T x, y;
    // ...
};

我希望 Vec2Vec2 之间的总和结果为a Vec2,但 C++ 默认情况下不会这样做。

我的想法错了吗?
我应该尝试并实施这种行为吗?

我应该如何实施呢?一种方法可以是重载任何运算符,以便使用 autodecltype 或某些 自己动手类型的提升,但这种方式绝非微不足道,甚至不允许我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半仙 2024-10-26 15:59:11

我确实喜欢这样:

template<class V, class W>
struct vector_add;  

template<typename T, typename U, size_t N>
struct vector_add<Vec<T,N>, Vec<U,N> > {
    typedef BOOST_TYPEOF_TPL(T()+U()) value_type;
    typedef Vec<value_type, N> type;
};

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:

template<class V, class W>
struct vector_add;  

template<typename T, typename U, size_t N>
struct vector_add<Vec<T,N>, Vec<U,N> > {
    typedef BOOST_TYPEOF_TPL(T()+U()) value_type;
    typedef Vec<value_type, N> type;
};

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

荆棘i 2024-10-26 15:59:11

Vec2Vec2 是完全独立的类型,恰好是从同一模板创建的。如果您希望任何涉及这两者的操作成为可能,您需要自己实现。

您可以创建基于基本类型进行升级的通用运算符,或者您可以针对您需要的情况进行显式升级,这在 IMO 中更安全

Vec2<double> and Vec2<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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文