C++ 模板/泛型编程和重载运算符中如何处理混合数据类型?
例如,假设我们正在创建一个带有 x 和 y 参数的二维坐标类,并且我们想要添加它们:
template <class T>
class Cartesian {
public:
Cartesian();
Cartesian(T _x, T _y);
Cartesian<T> operator + (const Cartesian<T> & rhs);
// setters, getters
private:
T x, y;
};
+
运算符重载以添加两个坐标:
template <class T>
Cartesian<T> Cartesian<T>::operator + (const Cartesian<T> & rhs) {return Cartesian(x+rhs.x,y+rhs.y);}
现在,我们实例化四个点:两个具有 int
系数;另外两个带有float
:
int main() {
Cartesian<int> i1(1,2), i2(3,4);
Cartesian<float> f1(5.7, 2.3), f2(9.8, 7.43);
添加两个整数没有问题,添加两个 float 也是如此。但是,如果我们想将一个 int 添加到一个 float 怎么办?即使在四年级的教室里,这也不是问题,但在这里……
(i1 + i2); // ok
(f1 + f2); // ok
(i1 + f2); // uh oh!!!
有没有简单的方法来处理这种情况?谢谢! :)
最佳答案
您可以免费使用 operator+
过载。
template <class T, class U>
typename std::enable_if<std::is_arithmetic<T>::value &&
std::is_arithmetic<U>::value, Cartesian<std::common_type_t<T, U>>>::type
operator + (Cartesian<T> const & lhs, Cartesian<U> const & rhs)
{
return Cartesian<std::common_type_t<T, U>>(lhs.x+rhs.x,lhs.y+rhs.y);
}
替换std::common_type_t<T, U>
通过 typename std::common_type<T,U>::type
如果是 C++14 之前的版本。
现在您可以执行上述操作:
Cartesian<int> i1(1, 2), i2(3, 4);
Cartesian<float> f1(5.7, 2.3), f2(9.8, 7.43);
auto a = i1 + i2; // a === Cartesian<int>
auto b = f1 + f2; // b === Cartesian<float>
auto c = i1 + f2; // c === Cartesian<float>
关于c++ - 混合模板化参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35905649/