从数组的类型中找到元素的类型 [英] Find the type of the elements from the type of the array
问题描述
假设我有一个类型为 T
的类型,保证它是一个数组(例如 int [32]
) 。我如何从数组的类型中获取元素的类型?
Suppose I have a type T
which is guaranteed to be an array (eg. int[32]
). How do I get the type of the elements from the type of the array?
我找到了一种方法,但是它涉及到声明一个虚拟临时变量,我希望避免:
I found a way to do it, but it involves declaring a dummy temporary variable, which I would like to avoid:
#include <iostream>
#include <typeinfo>
using namespace std;
template <typename T>
string getArrayType() {
// Is there a better way to do this?
T dummy;
return typeid(dummy[0]).name();
}
int main() {
cout << getArrayType<int[1]>() << endl; // i
cout << getArrayType<float[1]>() << endl; // f
}
推荐答案
您可以使用 std :: remove_all_extents
You could use std::remove_all_extents
as well
return typeid(typename std::remove_all_extents<T>::type).name();
此文档的状态
如果
T
是某个类型为X
的多维数组,则提供成员typedeftype
等于X
,否则类型为T
。
If
T
is a multidimensional array of some typeX
, provides the member typedeftype
equal toX
, otherwise type isT
.
因此它将删除数组类型以获取该数组中包含的基础类型
So it will remove the array type to get at the underlying type contained within that array
这篇关于从数组的类型中找到元素的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!