[英]How to pass a row of boost::multi_array and std::vector by reference to the same template function?
我对这段代码有问题:
#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&
更改为Vec
,它对boost :: multi_array起作用,但是std :: vector按值传递,这不是我想要的。 如何在不编写两个模板的情况下实现目标?
问题是,对于NumDims> 1 , operator[]
返回一个类型为template subarray<NumDims-1>::type
的临时对象。
一个(不太好)解决方案将是如下所示:
typedef boost::multi_array<double, 2> MA;
MA m1;
MA::reference ref = m1[0];
foo(ref, 5); // ref is no temporary now
另一种方法是包装你的实现并为多数组的情况提供重载....例如:
(注意:我没有看到如何使用boost::multi_array<T,N>::reference
来使用重载,请不要使用此detail::
version;
template<class T>
void foo_impl(T x, size_t N) {
for (size_t i = 0; i < N; ++i) {
x[i] = i;
}
}
template<class T>
void foo(T& t, size_t n) {
foo_impl<T&>(t, n);
}
template<typename T, size_t size>
void foo(boost::detail::multi_array::sub_array<T, size> r, size_t n) {
foo_impl(r, n);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.