在同一函数中使用提升multi_array及其视图

Using boost multi_array and its views in the same function

本文关键字:multi array 视图 函数      更新时间:2023-10-16

multi_array视图具有许多与multi_array相同的方法。他们是否有一个共同的基础,我可以通过参考使用?

void count(Type a) {
//         ^^^^ what should I use here?
    cout << a.num_elements() << endl;
}
int main() {
    boost::multi_array<int, 2> a;
    count(a);
    count(a[indices[index_range()][index_range()]]);
}

不,没有共同的基础。您必须使用模板。查看多阵列概念和升压概念检查库。

具体来说,你需要这样做:

template<ArrayType>
void count(ArrayType&& a) {
    cout << a.num_elements() << endl;
}

而且由于该操作是非修改的,因此最好void count(ArrayType const& a).

<小时 />

在我的多维数组库中,有一个共同的基础,因此您可以通过这种方式避免一些代码膨胀。我仍然会使用模板版本,因为它在概念上更正确。

#include<multi/array.hpp>  // from https://gitlab.com/correaa/boost-multi
#include<iostream>
namespace multi = boost::multi;
template<class Array2D> 
auto f1(Array2D const& A) {
    std::cout<< A.num_elements() <<'n';
}
auto f2(multi::basic_array<double, 2> const& A) {
    std::cout<< A.num_elements() <<'n';
}
int main() {
    multi::array<double, 2> A({5, 5}, 3.14);
    f1( A );  // prints 25
    f2( A );  // prints 25
    f1( A({0, 2}, {0, 2}) );  // a 2x2 view // prints 4
    f2( A({0, 2}, {0, 2}) );                // prints 4
}

https://godbolt.org/z/5djMY4Eh8