【问题标题】:How to declare "using" for "std::array" using template如何使用模板为“std::array”声明“使用”
【发布时间】:2019-10-10 11:38:24
【问题描述】:

例如我有这样的代码:

template<typename A, typename B>
using Map = std::map<A, B>;

template<typename A, typename B>
using UnorderedMap = std::unordered_map<A, B>;

我想为std::array 做同样的事情,即:

template<typename A, typename B>
using Array = std::array<A, B>;

但是如果我这样做,我会得到一个编译器错误:

错误 C2993:“B”:非类型模板参数“_Size”的非法类型

错误 C2955: 'std::array': 使用类模板需要模板

argument list array(21): message : see declaration of 'std::array'

有什么方法可以声明一个Array,它会在后台使用std::array

最后我想使用像Array&lt;int, 7&gt; items 这样的数组而不是std::array&lt;int, 7&gt; items

【问题讨论】:

    标签: c++ arrays templates std stdarray


    【解决方案1】:

    std::array 的第二个模板参数是non-type template parameter,类型为std::size_t。应该是

    template<typename A, std::size_t B>
    using Array = std::array<A, B>;
    

    【讨论】:

      【解决方案2】:

      嗯,std::array 的第二个模板参数不是类型而是size_t,所以语法应该是

                           vvvvvv
      
      template<typename T, size_t S>
      using Array = std::array<T, S>;
      

      【讨论】:

        猜你喜欢
        • 2021-12-31
        • 2016-03-15
        • 2021-10-11
        • 1970-01-01
        • 2019-04-08
        • 2017-12-02
        • 2019-04-07
        • 2014-02-05
        • 1970-01-01
        相关资源
        最近更新 更多