【问题标题】:Is there an elegant way to declare a set of functions with the same template parameters?有没有一种优雅的方式来声明一组具有相同模板参数的函数?
【发布时间】: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 &lt;typename T, typename U&gt;。我希望我能做这样的事情:

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 &lt;typename T, typename U&gt;行真的那么麻烦吗? C++ 模板元编程很冗长;我们都必须忍受这一点。
  • 1.宏是邪恶的。 2. 你的代码应该清楚地说明它在做什么并且易于阅读。因此,只需对每个运算符使用完整的调用。

标签: c++ templates


【解决方案1】:

您可以通过内联定义运算符来保存一个模板参数:

template <typename T>
struct Vec {
    T x, y; 
    template<class U> auto operator+(Vec<U> const& v)
    { return Vec<decltype(x + v.x)>{x + v.x, y + v.y};}
    template<class U> auto operator-(Vec<U> const& v)
    { return Vec<decltype(x - v.x)>{x - v.x, y - v.y};}
};

如果您完全想避免编写重复的代码,宏将是一种避免这种情况的方法(这是否是一种好的做法,以及它是否有助于或干扰理解代码,可能是品味和上下文的问题)

【讨论】:

    猜你喜欢
    • 2013-02-07
    • 2019-01-12
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 2011-01-31
    • 2016-07-08
    • 2019-03-24
    • 1970-01-01
    相关资源
    最近更新 更多