将2d std :: array传递给函数cpp

时间:2016-08-16 21:29:43

标签: c++ arrays c++11

我正在尝试在c ++中编写一个函数,该函数将采用2个输入std :: arrays,并通过矩阵乘法返回产品数组。但是,该函数不能采用不同尺寸的数组(例如4x4工作,3x4不工作)

这是代码:

#include <iostream> 
#include <array>


template <std::size_t SIZE>
void dot(std::array<std::array<double, SIZE>, SIZE>& array1, 
     std::array<std::array<double, SIZE>, SIZE>& array2)
{
  int x1 = array1.size();
  int y1 = array1[0].size();


  int x2 = array2.size();
  int y2 = array2[0].size();
}

int main()
{
  using std::array;
  array<array<double, 4>, 4> syn0 = {{ {1,2,4},
                       {2,3,4},
                       {6,8,6},
                       {1,2,4} }};
  dot(syn0, syn0);
  return 0;
}

使用此question中提出的模板示例,它将接受代码中的4x4等数组。

将矩阵更改为不相等的数字会产生以下错误:

newer.cpp: In function ‘int main()’:
newer.cpp:23:21: error: too many initializers for ‘std::__array_traits<std::array<double, 4ul>, 3ul>::_Type {aka std::array<double, 4ul> [3]}’
            {1,2,4} }};
                     ^
newer.cpp:24:17: error: no matching function for call to ‘dot(std::array<std::array<double, 4ul>, 3ul>&, std::array<std::array<double, 4ul>, 3ul>&)’
   dot(syn0, syn0);
                 ^
newer.cpp:24:17: note: candidate is:
newer.cpp:6:6: note: template<long unsigned int SIZE> void dot(std::array<std::array<double, SIZE>, SIZE>&, std::array<std::array<double, SIZE>, SIZE>&)
 void dot(std::array<std::array<double, SIZE>, SIZE>& array1, 
      ^
newer.cpp:6:6: note:   template argument deduction/substitution failed:
newer.cpp:24:17: note:   deduced conflicting values for non-type parameter ‘SIZE’ (‘4ul’ and ‘3ul’)
   dot(syn0, syn0);
                 ^
newer.cpp:24:17: note:   ‘std::array<std::array<double, 4ul>, 3ul>’ is not derived from ‘std::array<std::array<double, SIZE>, SIZE>

我假设这样做的原因是模板只分配一个变量,所以如果我将2分配给同一个变量,它会抛出错误。我测试了是否可以为两个不同的变量堆叠模板,但这是不可能的。

如何允许该函数采用任意大小的二维数组而不会导致该错误?

1 个答案:

答案 0 :(得分:3)

似乎你真的很亲密。

您只需将SIZE2作为参数添加到模板中:

template <std::size_t SIZE,std::size_t SIZE2>
void dot(std::array<std::array<double, SIZE>, SIZE2>& array1, 
     std::array<std::array<double, SIZE>, SIZE2>& array2)

它编译好了 您的syn0大小错误

int main()
{
  using std::array;
  array<array<double, 3>, 4> syn0 = {{ {1,2,4},
                       {2,3,4},
                       {6,8,6},
                       {1,2,4} }};
  dot(syn0, syn0);
  return 0;
}