2

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()]]);
}
cambunctious
  • 8,391
  • 5
  • 34
  • 53

2 Answers2

1

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

cambunctious
  • 8,391
  • 5
  • 34
  • 53
0

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

alfC
  • 14,261
  • 4
  • 67
  • 118