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()]]);
}
2
  • For generic types, use templates. Boost doesn't often favour runtime polymorphism Commented Jul 12, 2016 at 11:26
  • I was afraid of that Commented Jul 12, 2016 at 11:29

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.