如何用泛型类中的友元函数重载操作符
How to overload an operator with a friend function in a generic class?
我写了一个矩阵类。我重载了运算符+,这样用户就可以写:矩阵+ 2。我希望用户也写:2 +矩阵。
对于标准格式(即对象调用2),我写了一个标准的操作符重载函数。它的工作原理。
template<typename T>
Matrix<T> Matrix<T>::operator+(const T& rhs) const
{
Matrix result(rows, cols, 0.0);
for (unsigned i = 0; i < rows; ++i)
{
for (unsigned j = 0; j < cols; ++j)
{
result(i,j) = (*this)(i, j) + rhs;
}
}
return result;
}
现在对于另一阶(即2 +矩阵),我写了朋友函数:
// Friend Functions that allow the user to write expressions in a different order
template<typename T>
friend Matrix<T> operator+(const T& type, const Matrix<T>& matrix);
和实现如下:
template<typename T>
Matrix<T> operator+(const T& type, const Matrix<T>& matrix)
{
return matrix + type;
}
当我尝试写2 +矩阵(在main()),我得到一些错误。
我总是在使用泛型类的友元函数时遇到问题,坦率地说,我一直不明白为什么它对我不起作用。
谁能解释一下我在这里做错了什么?
错误我得到:
智能感知:没有操作符"+"匹配这些操作数操作数类型为:int + Matrix
严重性代码描述项目文件行错误C2244 'Matrix::operator +':无法将函数定义与现有声明匹配
这看起来只是一个模板演绎错误;也就是说,编译器不能根据模板化的友元函数推断出正确的函数。
因为你的朋友函数是一个简单的函数,你可以在你的类/头文件中声明它,编译器应该能够正确地推断它(如果打开了优化,也可能内联它);只需在头文件中声明friend函数:
friend Matrix operator+(const T& type, const Matrix& matrix)
{
return matrix + type;
}
你不需要指定template
关键字,因为它在你的模板特化类中。
希望能有所帮助。
只需将成员函数更改为const
即可解决此问题。
template<typename T>
Matrix<T> Matrix<T>::operator+(const T& rhs) const
{
...
}
相关文章:
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- c++:可变模板和函数重载
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- 解决模板成员函数重载
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 推断模板化函数中的函数重载
- C++复制函数重载导致"must be a nonstatic member function"错误
- 为什么 std::sort 找不到合适的(静态成员)函数重载?
- 可变参数泛型 lambda 和函数重载
- C++中的函数重载和继承
- 当有右值构造函数可用时,为什么从右值调用类引用构造函数重载?
- C/C++ 可变参数宏函数重载
- 将基类的成员函数重载到其他派生类C++
- C++ 函数重载匹配
- C++函数重载,具体步骤是什么
- C++:使用 param pack 显式调用函数重载
- 隐式生成的函数重载用于右值参数?
- 使用函数重载输入运算符
- 运算符重载函数上的函数重载