【问题标题】:Is there a way to deduce a type of a single element of an array in c++有没有办法在c ++中推断出数组的单个元素的类型
【发布时间】:2016-09-21 13:33:17
【问题描述】:

我在推导 c++ 数组的单个元素的类型时遇到问题。

我想实现以下目标:

template <class T>
struct array_element { };

template <class T>
struct array_element<T[]> {
   using type = T;
};

int main() {
   int a[5] = {1, 2, 3, 4, 5};
   array_element<decltype(a)>::type element = a[0];
}

但是代码显然不能编译(int[5]不匹配T[])...

【问题讨论】:

    标签: c++ templates c++11 sfinae typetraits


    【解决方案1】:

    你需要一个额外的参数来进行专业化:

    template <class T, size_t N>
    struct array_element<T[N]> {
       using type = T;
    };
    

    或者:

    std::remove_reference<decltype(a[0])>::type element = a[0];
    

    或者:

    auto element = a[0];
    

    【讨论】:

    • 实际代码有点复杂(在模板参数内),使用decltype 的方法在那里不会很干净......但是你的建议和额外的专业化参数非常适合!
    【解决方案2】:

    使用std::remove_extent模板类(C++11)或std::remove_extent_t别名模板(C++14)获取数组元素的类型(都是are declared in type_traits header file):

    std::remove_extent<decltype(a)>::type element0 = a[0];
    
    std::remove_extent_t<decltype(a)> element1 = a[1];
    

    Live demo

    您也可以使用std::remove_all_extents (C++11) 或std::remove_all_extents_t (C++14) 到get a type of an element of a multidimensional array

    【讨论】:

    • 不错!我不知道这个!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2021-12-26
    • 2017-04-10
    • 1970-01-01
    相关资源
    最近更新 更多