Const vector of non-const objects

Viewed 15050

In defining a function in an interface :

virtual void ModifyPreComputedCoeffs ( std::vector < IndexCoeffPair_t > & model_ ) = 0;

we want to specify that the vector model_ should not be altered in the sense push_back etc operations should not be done on the vector, but the IndexCoeffPair_t struct objects in the model_ could be changed. How should we specify that ?

virtual void ModifyPreComputedCoeffs ( const std::vector < IndexCoeffPair_t > & model_ ) = 0;

does not work I think.

6 Answers

Here's a generic version of MahlerFive's answer:

template<typename T>
class Mutable {
    mutable T m_val;
public:
    constexpr Mutable(T const& val) : m_val(val) { }
    constexpr Mutable(T&& val) : m_val(val) { }

    // note: all member functions are `const`
    constexpr Mutable const& operator=(T const& val) const {
        m_val = val;
        return *this;
    }
    constexpr Mutable const& operator=(T&& val) const {
        m_val = val;
        return *this;
    }

    constexpr operator T&() const {
        return m_val;
    }
};

You can then use std::vector<Mutable<T>> const in your code, which will mostly behave as intended.

You can try to create const std::vector<YouType*>. Then you can't change the vector but you can change objects inside vector. But be accurate because you will modify original objects not copies.

Use smart pointers or raw pointers depends on your use cases: you have owning vector or just vector of observers.

Related