2012-12-15 50 views
0

我有一个用C++编写的程序,使用矩阵,我想打印出来。在程序中,矩阵是整型或无符号字符型。这是我现在用来执行打印的代码。C++模板方法选择正确的打印方式

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; 
     } 
} 

我的问题是,对于无符号字符矩阵,值不解释为数字。例如,对于零矩阵,输出不会显示在控制台上。有什么方法可以使用模板化方法中的类型信息来计算如何正确打印两种类型的矩阵?我是否必须求助于制作两种不同类型的打印方法,这些打印方法使用正确格式字符串的printf?

回答

2

如果它可以在矩阵中存在的唯一类型是整型然后只需将它转换为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; 
     } 
} 

如果这不是你想要什么,然后告诉我,我会提供另一种解决方案。


另一种解决方案是创建一个元函数来确定投什么:

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; 
     } 
} 

你也可以使用过载或enable_if。

+0

这会为我目前所做的工作,但我想知道是否还有一个更一般的解决方案。如果矩阵条目可以是浮点类型,你会怎么做? – martega

+0

@martega更新。 – Pubby

+0

谢谢!这并不像我认为会是大声笑那么容易或者美丽。 – martega