使用模板 C++ 重载运算符
Overloading operator using templates c++
我正在制作一个矩阵库,我希望能够做类似的事情
Matrix<double> = Matrix<int> + Matrix<double>
这可能吗?
这是我现在拥有的:
template<typename T>
Matrix<T>& Matrix<T>::operator+(const Matrix& rhs) {
if(w != rhs.w || h != rhs.h) {
printf("e[31m[ERROR] Arithmetic Error: attempted to add %dx%d matrix to %dx%d matrixe[0mn", w, h, rhs.w, rhs.h);
}
else {
for(uint32_t i = 0;i < size;++i) {
m[i] += rhs.m[i];
}
}
return *this;
}
您可以制作operator+
模板,然后它可以接受Matrix
的其他实例化。
例如
template<typename T>
template<typename X>
Matrix<T>& Matrix<T>::operator+(const Matrix<X>& rhs) {
if(w != rhs.w || h != rhs.h) {
printf("e[31m[ERROR] Arithmetic Error: attempted to add %dx%d matrix to %dx%d matrixe[0mn", w, h, rhs.w, rhs.h);
}
else {
for(uint32_t i = 0;i < size;++i) {
m[i] += rhs.m[i];
}
}
return *this;
}
请注意,对于当前的实现,您必须确认允许当前实例化访问其他实例化(如rhs.w
(的成员。不同的实例化被视为不同的类型。
模板免费函数可能会解决您的问题,例如:
template <typename T1, typename T2>
auto operator+(const Matrix<T1>& lhs, const Matrix<T2>& rhs)
{
if (lhs.w != rhs.w || lhs.h != rhs.h) {
throw std::runtime_error("Incompatible size");
}
using T = decltype(std::declval<T1>() + std::declval<T2>());
Matrix<T> res(lhs.w, lhs.h);
for (uint32_t i = 0; i != res.size; ++i) {
res.m[i] = lhs.m[i] + rhs.m[i];
}
return res;
}
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用