简体   繁体   中英

How to overload [] operator for mpf_t array in a template class in C++?

I am trying to develop a custom class in C++ which would contain a mpfr_t array.
The problem is, I do not know how to overload the [] operator to access array elements.
See the code below:

template <const unsigned int N>
class MyClass<mpfr_t, N> {
 private:
    mpfr_t array[N];
 public:
    mpfr_t& operator[] (const unsigned int i) const {
        assert(0 <= i && i < N);
        return array[i];

The problem with the code above is that I cannot use const and return a reference; as this would allow for potential value modification. What is usually done in such cases is that people write two versions of [] : one const for constant class instances returning a value (not a reference) and another non-const which returns the reference. However, I cannot return mpfr_t type - this is simply not allowed by the library design:

error: function cannot return array type 'mpfr_t' (aka '__mpfr_struct [1]')

I realise that the problem stems from wrapping a C -dedicated code into strictly C++ mechanism of operator overloading, but I wonder if there is any hack around it?

You can implement the const version of operator[] by returning a const reference, instead of a non-const one (as you do in the current version):

//-----vvvvvvv-----------------------------------vvvvv--
mpfr_t const & operator[] (const unsigned int i) const {
    assert(0 <= i && i < N);
    return array[i];
}

Note that you can still have the non-const overload as well:

mpfr_t & operator[] (const unsigned int i) {
// ...

The first overload will be chosen if your MyClass object is const .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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