c++ - 打印多种不同类型的数字限制

标签 c++ templates typedef

在下面的代码中,我定义了一个名为 my_typeunsigned int,我用它来打印类型本身的最大值:

#include <iostream>
#include <limits>
#include <cmath>
...
using namespace std;

int main() {
  typedef unsigned int my_type;

  const my_type max_int = numeric_limits<my_type>::max():

  cout << max_int << endl;
  return 0;
}

如何在不重复此代码的情况下对多种类型执行相同的操作?

我尝试创建一个字符串数组来存储 unsigned intlong 类型(作为示例),但这没有用:

string current_type[2] = {"unsigned int", "long"};
loop{
  typedef current_type[0..1] my_type;
  const my_type max_int = numeric_limits<my_type>::max();
}

我也尝试过使用模板,但不知道该怎么做。

这可能吗?

最佳答案

#include <iostream>
#include <limits>

using namespace std;
template <typename T>
void printMax()
{
    cout << numeric_limits<T>::max() << endl;
}

int main()
{
    printMax<unsigned int>();
    printMax<double>();
    return 0;
}

和:

$ g++ test.cpp && ./a.out
4294967295
1.79769e+308

关于c++ - 打印多种不同类型的数字限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35698393/

相关文章:

c++ - 尝试与 typedef 交 friend 时出现 "elaborated type refers to typedef"错误

c++ - 使用 ofstream 将数据写入其文件后更新 ifstream 对象

c++ - 我可以从类型列表中声明模板特化吗?

javascript - ExtJS X模板 : calling a template from another template

c - 头文件原型(prototype)中的未知类型名称

c++ - 在派生类中可见的私有(private) typedef

c++ - vector 迭代器不兼容(段错误)

c++ - 无法同时显示五个 Mat 图像(C++、OpenCV)

c++ - 无法在 QImage 上绘制或更改像素的颜色

c++ - 模板类方法特化