我有一个 3D 数组 double
秒。我想编写简单和通用的函数来打印它的二维切片。
代码:
#include <cstdio>
#include <boost/multi_array.hpp>
template<class M> // any model of MultiArray concept
void printFloatMatrix(typename M::template array_view<2u>::type matrix) {
using std::printf;
for(auto& row : matrix) {
for(auto& elem : row) {
printf("%5.3f ", elem);
}
printf("\n");
}
}
int main() {
typedef boost::multi_array<double,3> data_t;
data_t test_matrix{data_t::extent_gen()[10][10][2]};
// ...
using boost::indices;
using boost::multi_array_types::index_range;
printFloatMatrix(test_matrix[ indices[index_range()] [index_range()] [0] ]);
}
对于 GCC,这会产生错误消息:
test.cpp: In function ‘int main()’:
test.cpp:24:79: error: no matching function for call to ‘printFloatMatrix(boost::multi_array_ref<double, 3u>::array_view<2u>::type)’
test.cpp:24:79: note: candidate is:
test.cpp:5:6: note: template<class M> void printFloatMatrix(typename M::array_view<2u>::type)
为什么会出错?
为什么不 M
推断为 boost::multi_array_ref<double, 3u>
?
我如何编写可用的原型(prototype)?
最佳答案
我无法在这里拼出 C++ 类型推断失败的确切原因,但将函数原型(prototype)更改为 template<class M> void printFloatMatrix(const M& matrix)
成功了。
不过,原型(prototype)现在变得毫无用处。很有可能它会在未来咬我。随着概念的出现,这种情况有望得到解决,或者可以使用静态断言来解决。
感谢##c++
在 Freenode。
关于c++ - 如何将 Boost.MultiArray 的二维 View 作为函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9472098/