Ala*_*lan 1 c++ templates typedef
在下面的代码中我定义了一个unsigned int被调用的my_type,我用它来打印类型本身的最大值:
#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;
}
Run Code Online (Sandbox Code Playgroud)
如何在不重复此代码的情况下对多种类型执行相同操作?
我试图创建将存储类型的字符串数组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();
}
Run Code Online (Sandbox Code Playgroud)
我也试过使用模板,但无法弄清楚如何做到这一点.
这甚至可能吗?
#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;
}
Run Code Online (Sandbox Code Playgroud)
和:
$ g++ test.cpp && ./a.out
4294967295
1.79769e+308
Run Code Online (Sandbox Code Playgroud)