【问题标题】:How to take a 2D view of Boost.MultiArray as an argument into function?如何将 Boost.MultiArray 的 2D 视图作为函数的参数?
【发布时间】:2012-02-27 20:52:29
【问题描述】:

我有一个doubles 的 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&lt;double, 3u&gt;

如何编写可以工作的原型?

【问题讨论】:

标签: c++ boost c++11 type-inference boost-multi-array


【解决方案1】:

我无法在这里说明 C++ 类型推断失败的确切原因,但将函数原型更改为 template&lt;class M&gt; void printFloatMatrix(const M&amp; matrix) 有效。

不过,原型现在太宽了。很有可能它会在未来咬我。这种情况有望随着概念的出现而得到解决,或者可以通过静态断言来解决。

感谢 Freenode 的 ##c++

【讨论】:

  • 任何时候你有typename X::Y,你都会得到一个所谓的“不可演绎的上下文”,这意味着不能从传递的参数中推断出模板参数。您需要在调用站点指定类型,更改不可推导的上下文(就像您在此处所做的那样),或者提供另一个允许模板参数推导的参数。
  • 这一定与模板的图灵完备性和停机问题有关。谢谢,现在我明白了。
猜你喜欢
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 2020-03-22
相关资源
最近更新 更多