从数组的类型中找到元素的类型 [英] Find the type of the elements from the type of the array

查看:78
本文介绍了从数组的类型中找到元素的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类型为 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 的多维数组,则提供成员typedef type 等于 X ,否则类型为 T

If T is a multidimensional array of some type X, provides the member typedef type equal to X, otherwise type is T.

因此它将删除数组类型以获取该数组中包含的基础类型

So it will remove the array type to get at the underlying type contained within that array

这篇关于从数组的类型中找到元素的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆