我有一个依赖于一种类型(例如template <typename T> class Vector)的模板类。现在,我要重载算术操作符,这样:
示例:
Vector<float> fv = {1.5, 2.5};
Vector<int> iv = {1,2};
auto s1 = fv + iv; // s1 MUST be of type Vector<float> == {2.5, 4.5}
auto s2 = iv + fv; // s2 MUST be of type Vector<float> == {2.5, 4.5}我认为,在实现矩阵、向量、多项式等的通用数学库中,这将是一个在可用性方面产生差异的特性。
我找到了三种在C++11中获得这个结果的方法
->符号
模板汽车运算符+(ConstVector&LHS,ConstVector&RHS) -> Vector { Vector res(lhs);res += rhs;返回res;}declval
模板运算符+(const Vector&LHS,const Vector&RHS){ Vector res (lhs+rhs);res += rhs;返回res};declval作为默认类型arg
模板向量运算符+(ConstVector&LHS,ConstVector&rhs){ Vector;res += rhs;返回res;}在您看来,实现这种功能的最佳方法是什么?如果有第四个更好的解决方案,我会很感激的。
您认为这样的“互操作”操作人员是有价值的吗?
谢谢并致以最良好的问候,戴维德
发布于 2015-12-31 16:43:18
这些操作人员是否是“好主意”取决于您的用例。但是,如果您想实现它们,我建议您使用一个从std::common_type派生的特性类来获得更多的控制:
template<typename T, typename U>
struct VectorCommonType : std::common_type<T,U> {};
template<typename T, typename U>
using VectorCommonTypeT = Vector<typename VectorCommonType<T,U>::type>;这样,您(或类的用户)就可以在需要时对其进行专门化。像这样使用它:
template<typename T, typename U>
VectorCommonTypeT<T,U> operator+(const Vector<T> &lhs, const Vector<U> &rhs)
{
VectorCommonTypeT<T,U> res(lhs);
res += rhs;
return res;
}https://stackoverflow.com/questions/34546867
复制相似问题