代码之家  ›  专栏  ›  技术社区  ›  zoecarver

模板数组长度作为参数

  •  0
  • zoecarver  · 技术社区  · 7 年前

    争论

    template <class T>
    void alloc_arr (int l) {
        std::allocator<T[l]> a;
    }
    
    alloc_arr<int[]>(64);
    

    它不起作用,因为实例化的类型必须在编译时修复( T[l] 不固定)。

    是否有其他方法不需要在类型中指定长度( <T[64]> )?

    2 回复  |  直到 7 年前
        1
  •  5
  •   max66    7 年前

    是否有其他方法不需要在类型()中指定长度?

    在某种程度上,您需要将其作为模板参数传递

    template <typename T, std::size_t Dim>
    void alloc_arr ()
     {
       std::allocator<T[Dim]> a;
       // ...  
     }
    

    或者,如果您至少可以使用C++11,也可以从参数的类型推断它;举例来说,

    template <typename T, std::size_t Dim>
    void alloc_arr (std::integral_constant<std::size_t, Dim> const &)
     {
       std::allocator<T[Dim]> a;
       // ...  
     }
    

    template <typename T, typename U>
    void alloc_arr (U const &)
     {
       std::allocator<T[U::value]> a;
       // ...  
     }
    

    使命感 alloc_arr 用一个 std::integral_constant<std::size_t, 5u>{} ,举例来说。

        2
  •  1
  •   Lourens Dijkstra    7 年前

    template parameter :

    template <class T, size_t size>
    void alloc_arr() { ... }
    

    这是唯一的办法。几天前我发现通过一个 constexpr lambda Trying to pass a constexpr lambda and use it to explicitly specify returning type

    int ; 不 int[] .

    alloc_arr<int, 64>();