Wie kann ich eine Reihe von Boost :: Multi_Array und std :: vector unter Bezugnahme auf die gleiche Vorlagenfunktion übergeben?
-
22-09-2019 - |
Frage
Ich habe ein Problem mit diesem Stück Code:
#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;
}
Wenn ich versuche, es mit GCC zu kompilieren, bekomme ich den Fehler:
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>]'
Es funktioniert wie erwartet für Boost :: multi_array, wenn ich den Typ des ersten Funktionsarguments ändere foo
aus Vec&
zu Vec
, Aber dann wird der std :: vector von Wert übergeben, was ich nicht will. Wie kann ich mein Ziel erreichen, ohne zwei Vorlagen zu schreiben?
Lösung
Das Problem ist das für Numdims> 1, operator[]
Gibt ein temporäres Objekt vom Typ zurück template subarray<NumDims-1>::type
.
Eine (nicht so schöne) Arbeit wäre das folgende:
typedef boost::multi_array<double, 2> MA;
MA m1;
MA::reference ref = m1[0];
foo(ref, 5); // ref is no temporary now
Eine Alternative wäre, Ihre Implementierung zu wickeln und eine Überladung für den Multi-Array-Fall bereitzustellen.
(Hinweis: Ich habe nicht gesehen, wie ich die Überlastung zum Arbeiten bringen kann boost::multi_array<T,N>::reference
, Bitte setzen Sie es damit nicht produktiv ein detail::
Ausführung ;)
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);
}