例如:
int a = 12;
cout << typeof(a) << endl;
预期的输出:
int
例如:
int a = 12;
cout << typeof(a) << endl;
预期的输出:
int
当前回答
涉及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;
}
其他回答
非常丑陋,但如果你只想要编译时信息(例如调试):
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*>'
Try:
#include <typeinfo>
// …
std::cout << typeid(a).name() << '\n';
您可能必须在编译器选项中激活RTTI才能使其工作。此外,它的输出取决于编译器。它可能是一个原始类型名称或名称混乱符号或介于两者之间的任何东西。
涉及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;
}
您可以使用模板。
template <typename T> const char* typeof(T&) { return "unknown"; } // default
template<> const char* typeof(int&) { return "int"; }
template<> const char* typeof(float&) { return "float"; }
在上面的例子中,当类型不匹配时,它将打印“unknown”。
一个没有函数重载的更通用的解决方案:
template<typename T>
std::string TypeOf(T){
std::string Type="unknown";
if(std::is_same<T,int>::value) Type="int";
if(std::is_same<T,std::string>::value) Type="String";
if(std::is_same<T,MyClass>::value) Type="MyClass";
return Type;}
这里的MyClass是用户定义的类。这里还可以添加更多的条件。
例子:
#include <iostream>
class MyClass{};
template<typename T>
std::string TypeOf(T){
std::string Type="unknown";
if(std::is_same<T,int>::value) Type="int";
if(std::is_same<T,std::string>::value) Type="String";
if(std::is_same<T,MyClass>::value) Type="MyClass";
return Type;}
int main(){;
int a=0;
std::string s="";
MyClass my;
std::cout<<TypeOf(a)<<std::endl;
std::cout<<TypeOf(s)<<std::endl;
std::cout<<TypeOf(my)<<std::endl;
return 0;}
输出:
int
String
MyClass