例如:
int a = 12;
cout << typeof(a) << endl;
预期的输出:
int
例如:
int a = 12;
cout << typeof(a) << endl;
预期的输出:
int
当前回答
不要忘记包含<typeinfo>
我相信您所指的是运行时类型标识。你可以通过做来达到以上目的。
#include <iostream>
#include <typeinfo>
using namespace std;
int main() {
int i;
cout << typeid(i).name();
return 0;
}
其他回答
涉及RTTI (typeid)的其他答案可能是您想要的,只要:
您可以承担内存开销(对于某些编译器,这可能相当大) 编译器返回的类名很有用
另一种选择(类似于Greg Hewgill的答案)是建立一个特征的编译时表。
template <typename T> struct type_as_string;
// declare your Wibble type (probably with definition of Wibble)
template <>
struct type_as_string<Wibble>
{
static const char* const value = "Wibble";
};
注意,如果你将声明包装在宏中,你将在声明带有多个参数的模板类型时遇到麻烦(例如std::map),这是由于逗号的原因。
要访问变量类型的名称,您所需要的是
template <typename T>
const char* get_type_as_string(const T&)
{
return type_as_string<T>::value;
}
考虑下面的代码:
#include <iostream>
int main()
{
int a = 2; // Declare type "int"
std::string b = "Hi"; // Declare type "string"
long double c = 3438; // Declare type "long double"
if(typeid(a) == typeid(int))
{
std::cout<<"int\n";
}
if(typeid(b) == typeid(std::string))
{
std::cout<<"string\n";
}
if(typeid(c) == typeid(long double))
{
std::cout<<"long double";
}
return 0;
}
我相信你想要整个单词(而不是只打印int的缩写形式(即I),你想要int),这就是为什么我做了if。
对于一些变量(字符串,long double等…)比较它们的简写形式不会输出预期的结果),您需要将应用typeid操作符的结果与特定类型的typeid进行比较。
从cppreference:
返回一个实现定义的以空结束的字符串,包含类型的名称。不提供任何保证;特别地,返回的字符串对于多个类型是相同的,并且在同一个程序的调用之间会发生变化。
在我看来,Python在这种情况下比c++更好。Python有内置的type函数,可以直接访问变量的数据类型。
不要忘记包含<typeinfo>
我相信您所指的是运行时类型标识。你可以通过做来达到以上目的。
#include <iostream>
#include <typeinfo>
using namespace std;
int main() {
int i;
cout << typeid(i).name();
return 0;
}
Try:
#include <typeinfo>
// …
std::cout << typeid(a).name() << '\n';
您可能必须在编译器选项中激活RTTI才能使其工作。此外,它的输出取决于编译器。它可能是一个原始类型名称或名称混乱符号或介于两者之间的任何东西。
非常丑陋,但如果你只想要编译时信息(例如调试):
auto testVar = std::make_tuple(1, 1.0, "abc");
decltype(testVar)::foo= 1;
返回:
Compilation finished with errors:
source.cpp: In function 'int main()':
source.cpp:5:19: error: 'foo' is not a member of 'std::tuple<int, double, const char*>'