cambunctious
cambunctious

Reputation: 9572

Using boost multi_array and its views in the same function

A multi_array view has many of the same methods as a multi_array. Do they have a common base that I can use by reference?

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

Upvotes: 2

Views: 66

Answers (2)

alfC
alfC

Reputation: 16242

To be concrete, you need to do this:

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

and since the operation is non-modifying, better yet void count(ArrayType const& a).


In my multidimensional array library, there is a common base, so you could avoid a bit of code bloating this way. I would still use the template version because it is conceptually more correct.

#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

Upvotes: 0

cambunctious
cambunctious

Reputation: 9572

No, there is no common base. You have to use templates. Check out MultiArray Concept and The Boost Concept Check Library.

Upvotes: 1

Related Questions