推断模板参数对象成员的类型

Deduce type of a member of a template argument object

有这个功能:

template <typename T>
T operator-(const T vector)
{}

我想强制 T 有 xy 成员,并且它们是算术的。 我试图通过 std::declval<T>:

template <typename T,
  typename = typename 
    std::enable_if<std::is_arithmetic<std::declval<T>.x>::value>::type,
  typename = typename 
    std::enable_if<std::is_arithmetic<std::declval<T>.y>::value>::type>
T operator-(const T vector)
{}

但我得到的只是无法推断类型:error: insufficient contextual information to determine type。模板参数对象成员的类型完全可以推导出来吗?

我认为你实际上并不想强制它们是算术的。您希望函数模板主体中的关键表达式格式正确。在那种情况下,按照

的方式去做一些事情
template <typename T>
auto operator-(const T& vector)
  -> decltype(void(x - vector.x), void(y - vector.y), vector)
{/* ... */}

如果您宁愿坚持使用正确的代码版本,用 decltype(std::declval<T>().x)decltype(T::x) 代替 std::declval<T>.xy 也一样)就足够了:

template <typename T,
  typename = std::enable_if_t<std::is_arithmetic<decltype(T::x)>{}>,
  typename = std::enable_if_t<std::is_arithmetic<decltype(T::x)>{}>>
T operator-(const T vector)
{}