如何将 Boost.MultiArray 的二维视图作为参数传递给函数?

3

我有一个由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>

我该如何编写能够正常工作的原型?


1个回答

1

我无法准确拼写C++类型推断失败的原因,但将函数原型更改为template<class M> void printFloatMatrix(const M& matrix)就可以解决。

现在原型过于宽泛,未来很可能会给我带来麻烦。随着概念的出现,这种情况有望得到解决,或者可以通过静态断言进行解决。

感谢Freenode上的##c++


4
每当你遇到 typename X::Y,你就会得到所谓的“无法推导上下文”,这意味着不能从传递给该参数的参数中推断出任何模板参数。你需要在调用处指定类型、更改该不可推断上下文(就像你在这里所做的那样),或者提供另一个参数来允许模板参数推导。 - Xeo
那一定与模板的图灵完备性和停机问题有关。谢谢,现在我明白了。 - ulidtko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接