c++ 如何将Boost.MultiArray的2D视图作为函数的参数?

7eumitmz  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(63)

我有一个double s的3D数组。我想写一个简单的通用函数来打印它的2D切片。
代码:

#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>
我该如何写出可行的原型?

ctrmrzij

ctrmrzij1#

我无法拼写C++类型推断失败的确切原因,但将函数原型更改为template<class M> void printFloatMatrix(const M& matrix)有效。
不过,原型现在是无用的宽。很有可能它会在未来咬我。这种情况有望随着概念的出现而得到解决,或者可以通过静态Assert来解决。
感谢Freenode的##c++

k4aesqcs

k4aesqcs2#

当然,你必须限制你的论点:

template<class M,
  std::enable_if_t<M::dimensionality == 2 and std::is_same_v<typename M::element, double>, int> =0
> 
void printFloatMatrix(const M& matrix)

字符串

相关问题