传递带有常量作为参数的模板化类

时间:2014-09-12 19:47:56

标签: c++ templates constants compile-time-constant

我的模板类如下所示:

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

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

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

3 个答案:

答案 0 :(得分:2)

将模板类operator<<(ostream&)的{​​{1}}重载声明为模板,这应该是明显的解决方案

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

operator<<(ostream&)

答案 1 :(得分: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;
}

答案 2 :(得分:1)

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

template<unsigned WIDTH, unsigned HEIGHT, typename T>
std::ostream& operator<<(std::ostream &os, const matrix<WIDTH, HEIGHT, T> &m){
  // ...
  return os;
}
相关问题