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

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

我的模板类如下所示:

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/

相关文章:

c++ - 无法链接 ".o"目标文件

c++ - 将 typedef 作为类的非静态成员访问?

c++ - 当我在某些情况下使用模板参数时,编译器如何生成函数实例?

c++ - 返回对函数模板的引用

c++ - 具有 Const 成员的构造函数的语法

c++ - 如何将解码缓冲区从 ffmpeg 映射到 QVideoFrame?

c++ - Qt - 在触发 Action 中连接信号/插槽

c++ - 具有不同文本颜色的 QTextEdit (Qt/C++)

c++ - 编译器如何知道是否调用 const 重载?

c++ - 从只读内存中读取结构