C++ 如何获取变量的类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11310898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:01:55  来源:igfitidea点击:

How do I get the type of a variable?

c++variablestypeof

提问by 0x499602D2

In C++, how does one find the type of a variable?

在 C++ 中,如何找到变量的类型?

回答by Rich O'Kelly

You can use the typeid operator:

您可以使用typeid 运算符

#include <typeinfo>
...
cout << typeid(variable).name() << endl;

回答by 0x499602D2

For static assertions, C++11 introduced decltypewhich is quite useful in certain scenarios.

对于静态断言,C++11 引入了decltype这在某些场景中非常有用。

回答by Amit

If you have a variable

如果你有一个变量

int k;

You can get its type using

您可以使用

cout << typeid(k).name() << endl;

See the following thread on SO: Similar question

请参阅有关 SO 的以下主题:类似问题

回答by Emilio Garavaglia

The main difference between C++ and Javascript is that C++ is a static-typed language, wile javascript is dynamic.

C++ 和 Javascript 之间的主要区别在于 C++ 是一种静态类型语言,而 javascript 是动态的。

In dynamic typed languages a variable can contain whatever thing, and its type is given by the value it holds, moment by moment. In static typed languages the type of a variable is declared, and cannot change.

在动态类型语言中,一个变量可以包含任何东西,它的类型由它所保存的值决定,每时每刻。在静态类型语言中,变量的类型是声明的,不能改变。

There can be dynamic dispatch and object composition and subtyping (inheritance and virtual functions) as well as static-dispatch and supertyping (via template CRTP), but in any case the type of the variable must be known to the compiler.

可以有动态分派、对象组合和子类型(继承和虚函数)以及静态分派和超类型(通过模板 CRTP),但在任何情况下,编译器都必须知道变量的类型。

If you are in the position to don't know what it is or could be, it is because you designed something as the language has a dynamic type-system.

如果您不知道它是什么或可能是什么,那是因为您设计了一些东西,因为该语言具有动态类型系统。

If that's the case you had better to re-think your design, since it is going into a land not natural for the language you are using (most like going in a motorway with a caterpillar, or in the water with a car)

如果是这种情况,你最好重新考虑你的设计,因为它进入了一个与你使用的语言不自然的地方(最像带着毛毛虫在高速公路上,或在水中带着汽车)

回答by Pontus Gagge

Usually, wanting to find the type of a variable in C++ is the wrong question. It tends to be something you carry along from procedural languages like for instance C or Pascal.

通常,想要在 C++ 中查找变量的类型是错误的问题。它往往是你从诸如 C 或 Pascal 之类的过程语言中携带的东西。

If you want to code different behaviours depending on type, try to learn about e.g. function overloadingand object inheritance. This won't make immediate sense on your first day of C++, but keep at it.

如果您想根据类型编写不同的行为,请尝试了解例如函数重载对象继承。这在您学习 C++ 的第一天不会立即产生意义,但请坚持下去。

回答by Dan Truong

I believe I have a valid use case for using typeid(), the same way it is valid to use sizeof(). For a template function, I need to special case the code based on the template variable, so that I offer maximum functionality and flexibility.

我相信我有一个使用 typeid() 的有效用例,与使用 sizeof() 的方式相同。对于模板函数,我需要根据模板变量对代码进行特殊处理,以便提供最大的功能和灵活性。

It is much more compact and maintainable than using polymorphism, to create one instance of the function for each type supported. Even in that case I might use this trick to write the body of the function only once:

与使用多态性相比,为每种支持的类型创建函数的一个实例要紧凑和可维护得多。即使在那种情况下,我也可能使用这个技巧只编写一次函数体:

Note that because the code uses templates, the switch statement below should resolve statically into only one code block, optimizing away all the false cases, AFAIK.

请注意,因为代码使用模板,下面的 switch 语句应该静态解析为一个代码块,优化掉所有错误的情况,AFAIK。

Consider this example, where we may need to handle a conversion if T is one type vs another. I use it for class specialization to access hardware where the hardware will use either myClassA or myClassB type. On a mismatch, I need to spend time converting the data.

考虑这个例子,如果 T 是一种类型与另一种类型,我们可能需要处理转换。我将它用于类专业化以访问硬件,其中硬件将使用 myClassA 或 myClassB 类型。如果不匹配,我需要花时间转换数据。

switch ((typeid(T)) {
  case typeid(myClassA):
    // handle that case
    break;
  case typeid(myClassB):
    // handle that case
    break;
  case typeid(uint32_t):
    // handle that case
    break;
  default:
    // handle that case
}

回答by gohongyi

I'm not sure if my answer would help.

我不确定我的回答是否有帮助。

The short answer is, you don't really need/want to know the type of a variable to use it.

简短的回答是,您真的不需要/不想知道使用它的变量的类型。

If you need to give a type to a static variable, then you may simply use auto.

如果您需要为静态变量指定类型,那么您可以简单地使用 auto。

In more sophisticated case where you want to use "auto" in a class or struct, I would suggest use template with decltype.

在更复杂的情况下,您想在类或结构中使用“auto”,我建议使用带有 decltype 的模板。

For example, say you are using someone else's library and it has a variable called "unknown_var" and you would want to put it in a vector or struct, you can totally do this:

例如,假设您正在使用其他人的库,并且它有一个名为“unknown_var”的变量,并且您想将其放入向量或结构体中,您完全可以这样做:

template <typename T>
struct my_struct {
    int some_field;
    T my_data;
};
vector<decltype(unknown_var)> complex_vector;
vector<my_struct<decltype(unknown_var)> > simple_vector

Hope this helps.

希望这可以帮助。

EDIT: For good measure, here is the most complex case that I can think of: having a global variable of unknown type. In this case you would need c++14 and template variable.

编辑:为了更好的衡量,这是我能想到的最复杂的情​​况:有一个未知类型的全局变量。在这种情况下,您将需要 c++14 和模板变量。

Something like this:

像这样的东西:

template<typename T> vector<T> global_var;

void random_func (auto unknown_var) {
    global_var<decltype(unknown_var)>.push_back(unknown_var);
}

It's still a bit tedious but it's as close as you can get to typeless languages. Just make sure whenever you reference template variable, always put the template specification there.

它仍然有点乏味,但它尽可能接近无类型语言。只要确保每当您引用模板变量时,始终将模板规范放在那里。

回答by rad

#include <typeinfo>

...
string s = typeid(YourClass).name()

回答by Pikachu

You can definitely go for typeid(x).name()where x is the variable name. It actually returns a const char pointer to the data type. Now, look at the following code.

你绝对可以去typeid(x).name()x 是变量名的地方。它实际上返回一个指向数据类型的 const char 指针。现在,看看下面的代码。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n = 36;
    char c = 'A';
    double d = 1.2;
    if(*(typeid(n).name()) == 'i'){
        cout << "I am an Integer variable" << endl;
    }
    if(*((char *) typeid(d).name()) == 'd'){
        cout << "I am a Double variable" << endl;
    }
    if(*((char *) typeid(c).name()) == 'c'){
        cout << "I am a Char variable" << endl;
    }
    return 0;
}

Notice how first and second both if works.

注意 first 和 second 是如何工作的。

回答by Hymanw11111

If you need to make a comparison between a class and a known type, for example:

如果您需要在类和已知类型之间进行比较,例如:

class Example{};
...
Example eg = Example();

You can use this comparison line:

您可以使用此比较线:

bool isType = string( typeid(eg).name() ).find("Example") != string::npos;

which checks the typeidname contains the string type (the typeid name has other mangled data, so its best to do a s1.find(s2)instead of ==).

它检查typeid名称包含字符串类型(typeid 名称具有其他损坏的数据,因此最好使用 as1.find(s2)而不是==)。