Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pitfalls of implementing a reference getter with a const_cast of a const-ref getter

Tags:

c++

I have a class, say, vector<T>. I want to implement two getter methods, returning T& and const T& respectively. I do not want to implement both of them. Instead I'd like to implement only const version and then reuse its code in a non-const method with const_cast.

template<typename T>
class Vector {
public:
    T& operator[](size_t i) {
        return const_cast<T&>(
            static_cast<const Vector<T>*>(this)->operator[](i));
    }

    const T& operator[](size_t i) const {
        return data[i];
    }

private:
    T* data;
};

What are the possible pitfalls of this approach? Or, are there any methods to check that const_cast is legitimate in any exact case?

Finally, what are the good common ways to deal with such duplicated const/non-const code?

like image 445
Ivan Smirnov Avatar asked Dec 12 '25 13:12

Ivan Smirnov


1 Answers

One clean way is to delegate to a private template function which can deduce the constness of this:

#include <cstdint>

template<typename T>
class Vector {
public:
    T& operator[](std::size_t i) {
      return impl_indirection(this, i);
    }

    const T& operator[](std::size_t i) const {
      return impl_indirection(this, i);
    }

private:
  template<class MaybeConstVector>
    static decltype(auto) impl_indirection(MaybeConstVector* pv, std::size_t index)
  {
    return pv->data[index];
  }

  T* data;
};
like image 173
Richard Hodges Avatar answered Dec 15 '25 03:12

Richard Hodges



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!