我的模板类如下所示:
template<unsigned WIDTH, unsigned HEIGTH, typename T = int> class matrix { ... }
如此简单明了,模板参数决定了矩阵的大小。大小在逻辑上是恒定的,所以我实现它是恒定的。但是当我尝试编写一个接受我的矩阵
的函数时,我遇到了以下问题:
std::ostream& operator<<(std::ostream &os, const matrix &m){ ...}
像这样写,编译器理所当然地反对缺少模板参数......但是
std::ostream& operator<<(std::ostream &os, const matrix<unsigned, unsigned> &m){ ...}
触发此错误:error: expected a constant of type 'unsigned int', got 'unsigned> int'
这也是正确的,因为 matrix
需要常量,而不是类型。
如何处理?我确定我不是第一个遇到这个问题的人,解决这个传递常量参数化模板问题的最“规范”方法是什么?
最佳答案
声明您的 operator<<(ostream&)
为您的模板类重载 matrix
作为一个模板,这应该是这里显而易见的解决方案
template<unsigned WIDTH, unsigned HEIGTH, typename T = int>
class matrix
{
public:
T arr[WIDTH][HEIGTH];
};
template<unsigned WIDTH, unsigned HEIGTH, typename T>
std::ostream& operator<<(std::ostream &os, const matrix<WIDTH, HEIGTH,T> &m)
{
// formatting inserter of m onto os
return os;
}
int main()
{
matrix<10, 10> m;
std::cout << m << std::endl;
}
但一般来说,如果您的 operator<<(ostream&)
需要访问您的私有(private)数据(通常会),您最终会声明它为 friend 。如果您不想重复重新模板参数,请将 operator<<(ostream&)
矩阵类范围内的非成员 friend
template<unsigned WIDTH, unsigned HEIGTH, typename T = int>
class matrix
{
T arr[WIDTH][HEIGTH];
friend std::ostream& operator<<(std::ostream &os, const matrix &m)
{
// formatting inserter of m onto os
return os;
}
};
关于c++ - 传递带有常量作为参数的模板化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25815761/