问问题
396 次
3 回答
9
Use std::common_type
:
template <std::size_t s, typename L, typename R>
MyMathVector<typename std::common_type<L, R>::type, s> operator+(MyMathVector<L, s> const& l, MyMathVector<R, s> const& r)
{
// do addition
}
Ot in case of the member function (in the class body, where T
and s
are visible):
template <typename TRHS>
MyMathVector<typename std::common_type<T, TRHS>::type, s> operator+(MyMathVector<TRHS, s> const& rhs) const
{
// do addition
}
于 2012-07-31T15:51:13.073 回答
5
Use the std::common_type
trait to figure out the correct result type for a mixed operation.
The linked page even has an example that's very similar to your case.
于 2012-07-31T15:52:29.250 回答
4
Absolutely; use decltype
:
template<typename Other>
auto operator+(const MyMathVector<Other, size> &other)
-> MyMathVector<decltype(std::declval<T>() + std::declval<Other>()), size>;
As a non-member operator, it might be better to say what you mean by actually referencing a vector member:
template<typename size, typename L, typename R>
auto operator+(const MyMathVector<L, size> &l, const MyMathVector<R, size> &r)
-> MyMathVector<decltype(l[0] + r[0]), size>;
于 2012-07-31T15:53:03.540 回答