如何通过参考相同的模板函数传递一排BOOST :: MULTI_ARRAY和STD :: VECTOR?
-
22-09-2019 - |
题
我对此代码有问题:
#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
, ,但是随后按值通过的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::
版本 ;)
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);
}
不隶属于 StackOverflow