【发布时间】:2020-08-01 14:41:20
【问题描述】:
例如,假设我有一个简单的 2D 矢量模板结构:
template <typename T>
struct Vec { T x, y; };
还有一种通用的求和方式:
template <typename T, typename U>
constexpr auto operator+(const Vec<T>& u, const Vec<U>& v) {
return Vec<decltype(u.x + v.x)>{u.x + v.x, u.y + v.y};
}
但是对于所有其他基本操作(-、*、/ 等),我必须重写 template <typename T, typename U>。我希望我能做这样的事情:
template <typename T, typename U>
{
constexpr auto operator+(const Vec<T>& u, const Vec<U>& v) { /* ... */ };
constexpr auto operator-(const Vec<T>& u, const Vec<U>& v) { /* ... */ };
/* ... */
}
另外,正如thread 中所说,auto 在嵌套在 decl 说明符中时是不允许的,这意味着以下解决方案无效(即使它以某种方式编译):
constexpr auto operator+(const Vec<auto>& u, const Vec<auto>& v) { /* ... */ }
【问题讨论】:
-
也许使用宏?
-
我在想这个,但宏不被认为是邪恶的和不好的做法吗?
-
我应该说邪恶是主观的吗? :P 你想做的事情只能通过 C++ 中的宏来完成,如果有的话。
-
为每个操作员重复
template <typename T, typename U>行真的那么麻烦吗? C++ 模板元编程很冗长;我们都必须忍受这一点。 -
1.宏是邪恶的。 2. 你的代码应该清楚地说明它在做什么并且易于阅读。因此,只需对每个运算符使用完整的调用。