Pregunta

I have a program, written in C++, that uses matrices and I would like to print them out. In the program, matrices are either of type integer or unsigned char. This is the code I'm using right now to do the printing.

template<class T>
void print_matrix(const int& num_rows, const int& num_cols, T** M)
{
        for (int row = 0; row < num_rows; row++) {
                for (int col = 0; col < num_cols; col++) {
                        std::cout << std::setw(5) << M[row][col];
                }
                std::cout << std::endl;
        }
}

My problem is that for unsigned char matrices, the values aren't interpreted as numbers. For example, for the zero matrix, the output doesn't show up on the console. Is there any way I can use the type information in the templated method to figure out how to correctly print both types of matrices? Do I have to just resort to making two different types of printing methods that make use of printf with the correct format strings?

¿Fue útil?

Solución

If the only types which can exist in the matrix are integer types then just cast it to long:

template<class T>
void print_matrix(const int& num_rows, const int& num_cols, T** M)
{
        for (int row = 0; row < num_rows; row++) {
                for (int col = 0; col < num_cols; col++) {
                        std::cout << std::setw(5) << static_cast<long>(M[row][col]);
                }
                std::cout << std::endl;
        }
}

If this is not what you want then tell me and I'll provide another solution.


Another solution is to create a metafunction to determine what to cast to:

template<typename T>
struct matrix_print_type {
    typedef T type;
};
template<>
struct matrix_print_type<char> {
    typedef int type; // cast chars to ints
};
template<class T>
void print_matrix(const int& num_rows, const int& num_cols, T** M)
{
        for (int row = 0; row < num_rows; row++) {
                for (int col = 0; col < num_cols; col++) {
                        std::cout << std::setw(5) << static_cast<typename matrix_print_type<T>::type>(M[row][col]);
                }
                std::cout << std::endl;
        }
}

You could also use overloads or enable_if.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top