gpt4 book ai didi

C++模板方法选择正确的打印数据方式

转载 作者:行者123 更新时间:2023-11-28 03:26:12 30 4
gpt4 key购买 nike

我有一个用 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;
}
}

我的问题是,对于 unsigned char 矩阵,值不会被解释为数字。例如,对于零矩阵,输出不会显示在控制台上。有什么方法可以使用模板化方法中的类型信息来弄清楚如何正确打印两种类型的矩阵?我是否必须采用两种不同类型的打印方法来使用 printf 和正确的格式字符串?

最佳答案

如果矩阵中唯一可以存在的类型是整数类型,那么只需将其转换为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。

关于C++模板方法选择正确的打印数据方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13889592/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com