繁体   English   中英

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

[英]Using boost multi_array and its views in the same function

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()]]);
}

不,没有共同的基础。 你必须使用模板。 查看MultiArray 概念Boost 概念检查库

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM