【问题标题】:Array type deduction in a function template函数模板中的数组类型推导
【发布时间】:2012-06-26 03:02:15
【问题描述】:

我有一个模板方法如下:-

template<typename T, int length>
void ProcessArray(T array[length]) { ... }

然后我有使用上述方法的代码:-

int numbers[10] = { ... };
ProcessArray<int, 10>(numbers);

我的问题是为什么我必须明确指定模板参数。不能自动推导出来,这样我就可以使用如下:-

ProcessArray(numbers); // without all the explicit type specification ceremony

我确定我缺少一些基本的东西!备用一把锤子!

【问题讨论】:

    标签: c++ templates visual-c++ explicit-specialization


    【解决方案1】:

    您不能按值传递数组。在函数参数中,T array[length] 与T* array完全相同。没有长度信息可供推断。

    如果你想按值获取一个数组,你需要像std::array 这样的东西。否则,您可以参考,不会丢失尺寸信息:

    template<typename T, int length>
    void ProcessArray(T (&array)[length]) { ... }
    

    【讨论】:

      【解决方案2】:

      您缺少正确的参数类型:数组只能通过 reference 传递:

      template <typename T, unsigned int N>
      void process_array(T (&arr)[N])
      {
          // arr[1] = 9;
      }
      
      double foo[12];
      process_array(foo); // fine
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-27
        • 1970-01-01
        相关资源
        最近更新 更多