访问重载的模板函数
access overloaded template functions
大家好,我对如何访问像这样的重载模板函数感到困惑:
template <typename T>
friend istream& operator>> (istream& in, Matrix& right)
{
for(int i=0; i<right.rows*right.cols; i++)
cin >> right.elements[i];
}
带有如下函数:
template <typename T>
Matrix(T r, T c) {rows=r; cols=c; elements=new T[r*c];}
i was able do
Matrix <double> test(number, number)
例如,但我不知道如何使用模板化的>>操作符(或<<)或*或+…)任何帮助将不胜感激。谢谢!
我假设您正在声明一个具有类型参数T
的类模板Matrix
,并且您想使用已定义的operator>>
(您应该在问题中更明确地说明这一点):
template <typename T>
class Matrix {
int rows, cols;
T* elements;
public:
Matrix( int c, int r ); // Do you really want the number of
// rows/columns to be of type `T`??
// Note: removed template, you only want to befriend (and define)
// a single operator<< that takes a Matrix<T> (the <T> is optional
// inside the class braces
friend std::istream& operator>>( std::istream& i, Matrix& m )
{
// m.rows, m.cols and m.elements is accessible here.
return i;
}
};
使用起来很简单:
Matrix<double> m( 1, 2 );
std::cin >> m;
这不是唯一的选择,它只是最常见的一个。一般来说,类模板可以像上面的代码那样与单个(非模板化的)函数(将operator<<
和operator>>
看作函数)为友,或者它可能想与函数模板(所有实例化)或函数模板的特定实例化为友。
我在这里写了一篇很长的关于不同选项和行为的解释,我建议你读一读。
唯一的访问方式是这样的:
operator>> <YourType> (istream, param);
,但它显然破坏了操作符重载的所有优点。所以这个算子的定义有问题。也许Matrix是模板类型,它应该是
template <typename T>
operator>>(istream & in, Matrix<T> & right);
我在你的操作符定义中没有看到模板参数的使用,所以它有问题。
相关文章:
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- c++:可变模板和函数重载
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- 解决模板成员函数重载
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 推断模板化函数中的函数重载
- C++复制函数重载导致"must be a nonstatic member function"错误
- 为什么 std::sort 找不到合适的(静态成员)函数重载?
- 可变参数泛型 lambda 和函数重载
- C++中的函数重载和继承
- 当有右值构造函数可用时,为什么从右值调用类引用构造函数重载?
- C/C++ 可变参数宏函数重载
- 将基类的成员函数重载到其他派生类C++
- C++ 函数重载匹配
- C++函数重载,具体步骤是什么
- C++:使用 param pack 显式调用函数重载
- 隐式生成的函数重载用于右值参数?
- 使用函数重载输入运算符
- 运算符重载函数上的函数重载