在下面的代码中,我定义了一个名为 my_type
的 unsigned 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 int
和 long
类型(作为示例),但这没有用:
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/