mk1*_*k12 4 c++ generics math templates operator-overloading
我有一个Vector代表2D矢量的类.模板允许任何数字类型用于x和y分量.例如,我重载的算术运算符之一是*将向量与标量相乘:
template <typename T, typename U>
inline const Vector<T> operator*(const Vector<T>& vector, U scalar) {
return Vector<T>(vector.x * scalar, vector.y * scalar);
}
Run Code Online (Sandbox Code Playgroud)
(我还有一个函数,参数顺序相反scalar * Vector,除此之外Vector * scalar).
正如您所看到的,我使用<T, U>而不是简单地<T>使标量不必与Vector相同.当我没有这样做时,令人惊讶的Vector<double> * int是不会编译(我认为int会自动加宽).
无论如何,我不只是想回归一个Vector<T>.我想模仿内置类型并返回具有更高精度的那个,T或者U.例如,Vector<int> * double => Vector<double>同时Vector<double> * short => Vector<double>.
这可能吗?
您可以使用common_type或decltype烹饪能够为您提供最终类型的东西; 然后你必须创建实际的矢量:
template <typename A, typename B>
std::vector<typename std::common_type<A, B>::type>
operator*(std::vector<A> const & v, B const & x)
{
std::vector<typename std::common_type<A, B>::type> res;
res.reserve(v.size());
for (A a : v) res.push_back(a * x);
return res;
}
Run Code Online (Sandbox Code Playgroud)
使用decltype,您可以通过以下方式获取结果类型:
decltype(std::declval<A>() * std::declval<B>())
Run Code Online (Sandbox Code Playgroud)
对于这两个std::common_type和std::declval需要#include <type_traits>.
延迟返回类型(auto和->)你可以decltype直接使用函数参数,但使用std::declval感觉更卫生,因为它不需要你提供你的类型的实际实例(因此它甚至适用于这种情况下是不可能的).