我对这段代码有疑问:
#include <boost/multi_array.hpp>
#include <boost/array.hpp>
#include <vector>
#include <iostream>
template <typename Vec>
void foo(Vec& x, size_t N)
{
for (size_t i = 0; i < N; ++i) {
x[i] = i;
}
}
int main()
{
std::vector<double> v1(10);
foo(v1, 5);
std::cout << v1[4] << std::endl;
boost::multi_array<double, 2> m1;
boost::array<double, 2> shape;
shape[0] = 10;
shape[1] = 10;
m1.resize(shape);
foo(m1[0], 5);
std::cout << m1[0][4] << std::endl;
return 0;
}
试图用 gcc 编译它,我得到了错误:
boost_multi_array.cpp: In function 'int main()':
boost_multi_array.cpp:26: error: invalid initialization of non-const reference of type 'boost::detail::multi_array::sub_array<double, 1u>&' from a temporary of type 'boost::detail::multi_array::sub_array<double, 1u>'
boost_multi_array.cpp:7: error: in passing argument 1 of 'void foo(Vec&, size_t) [with Vec = boost::detail::multi_array::sub_array<double, 1u>]'
当我将函数的第一个参数的类型foo
从Vec&
to更改为 boost::multi_array 时,它按预期工作Vec
,但是 std::vector 是按值传递的,这不是我想要的。如何在不编写两个模板的情况下实现我的目标?