c++operator-overloadingmpfr

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?


Solution

  • 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.