【发布时间】:2020-10-15 22:00:36
【问题描述】:
我想实现一个包含一些数据类型名称的表,这样我就可以在cout我的函数的循环中使用它们。怎么做?我已经尝试过使用我的代码中的表格,但它不起作用。可能是指针的东西。
#include <iostream>
#include <limits>
#include <iomanip>
using namespace std;
template<typename T>
void sizeF(string opis) {
int x = sizeof(T);
if (x==1)
cout << "Rozmiar typu "+opis+" to " << x << " bajt.\n";
else if (x==2 || x==4)
cout << "Rozmiar typu "+opis+" to " << x << " bajty.\n";
else
cout << "Rozmiar typu "+opis+" to " << x << " bajtów.\n";
}
template<typename T>
void maxMinF(string opis)
{
cout << opis << ": minimalna wartosc: " << numeric_limits<T>::min() << ", maksymalna wartosc: " << numeric_limits<T>::max() << endl;
}
int main()
{
char tab[1][15] = {"short int"};
sizeF<tab[0]>(tab[0]);
sizeF<int>("int");
sizeF<unsigned long long>("unsigned long long");
sizeF<bool>("bool");
sizeF<char>("char");
sizeF<double>("double");
sizeF<long double>("long double");
sizeF<long long>("long long");
sizeF<short>("short");
sizeF<unsigned short>("usigned short");
cout << endl;
maxMinF<short int>("short int");
maxMinF<int>("int");
maxMinF<unsigned long long>("unsigned long long");
maxMinF<bool>("bool");
maxMinF<char>("char");
maxMinF<double>("double");
maxMinF<long double>("long double");
maxMinF<long long>("long long");
maxMinF<short>("short");
maxMinF<unsigned short>("usigned short");
return 0;
}
【问题讨论】:
-
您可以使用
std::type_info获取类型名。要使它们解构,您需要使用编译器内部的特殊函数(例如,abi::__cxa_demangle用于 GCC)。 -
在 C++ 中使用 std::vector<:variant unsigned long bool char double ...>>。如果 std::variant 不可用,您可以使用 boost::variant 或使用 union : ``` struct Type{ union { int i;无符号长长我; //其他类型 } enum class UsedType { IntType, ... } std::string data; };然后... std::vector
类型; ``` 您现在可以通过 UsedType 枚举来区分类型。 -
在
cout << "Rozmiar typu "+opis+" to " << x中,您不必要地创建了 2 个临时字符串。将它们直接传递给 cout 以避免那些临时字符串:cout << Rozmiar typu " << opis << " to " << x -
@GrzegorzGłowacki 你能告诉我更多关于 IntType 的信息以及接下来如何在我的函数中使用 std::vector
类型吗?