Search code examples
c++templatesconstantscompile-time-constant

passing a templated class with constants as an argument


My template class looks like this:

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

So plain and simple, the template arguments determine this size of the matrix. The size is logically constant, so I implemented it to be consant. But when I try to write a function that accepts my matrix, I run into the following problem:

std::ostream& operator<<(std::ostream &os, const matrix &m){ ...}

Writen like so, the compiler rightfully objects the lack of template arguments... But

std::ostream& operator<<(std::ostream &os, const matrix<unsigned, unsigned> &m){ ...}

triggers this error: error: expected a constant of type 'unsigned int', got 'unsigned> int'

Which is also kind of true, since matrix expects constants, not types.

How to deal with this? I'm sure I'm not the frst to encounter this problem, what's the most "canonical" way to approach this problem of passing constant-parametrized templates?


Solution

  • Option #1

    Declare the operator<< as a friend function in the scope of the matrix class:

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

    Option #2

    Make operator<< a function template as well:

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