0

我的模板类如下所示:

template<unsigned WIDTH, unsigned HEIGTH, typename T = int> class matrix { ... }

如此简单明了,模板参数决定了矩阵的大小。大小在逻辑上是恒定的,所以我实现它是恒定的。但是当我尝试编写一个接受 my 的函数时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需要常量,而不是类型。

如何处理?我确定我不是第一个遇到这个问题的人,解决传递常量参数化模板这个问题的最“规范”方法是什么?

4

3 回答 3

2

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&)需要访问您的私人数据(通常会),您最终会将其声明为朋友。如果您不想重复 remplate 参数,请将operator<<(ostream&)非成员朋友放在矩阵类的范围内

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;
     }
};
于 2014-09-12T19:54:41.947 回答
1

选项1

在类的范围内声明operator<<matrix元函数:

template<unsigned WIDTH, unsigned HEIGTH, typename T = int>
class matrix
{
    friend std::ostream& operator<<(std::ostream &os, const matrix& m)
    //                                                      ^^^^^^ plain name
    {
        return os;
    }
};

选项#2

制作operator<<一个函数模板:

template<unsigned WIDTH, unsigned HEIGHT, typename T>
std::ostream& operator<<(std::ostream &os, const matrix<WIDTH, HEIGHT, T>& m)
//                                                      ^^^^^  ^^^^^^  ^
{
    return os;
}
于 2014-09-12T19:53:26.210 回答
1

重载operator<<也需要是模板:

template<unsigned WIDTH, unsigned HEIGHT, typename T>
std::ostream& operator<<(std::ostream &os, const matrix<WIDTH, HEIGHT, T> &m){
  // ...
  return os;
}
于 2014-09-12T19:53:36.427 回答