jlack jlack - 4 months ago 12
C++ Question

Const method returning non-const reference to vector element

I'm having a hard time figuring out how to return a

non-const
reference to an element in a
std::vector
from a const class method. A simple example of what i'm going for is,

template<class T>
class MyClass
{
public:
MyClass : myVec(3)
{
}

T& x() const
{
return *(myVec.data())[0]
}

std::vector<T> myVec;
}


The behavior i'm going for is that i'd like to be able to do things like the following,

MyClass obj<double>;
obj.x() = 3.3;
assert(obj.x()==3.3)


Eigen gives the same type of behavior, but i've not been able to figure out how to get it to work. Thanks!

Answer

You could use const_cast, and it'll work here, (according to the usage shown). But you won't need it for this case.

You could(and should) add non-const member function overloading for it. Then const member function returns const reference, non-const member function returns non-const reference. The appropriate one will be invoked via overload resolution.

const T& x() const
{
   return myVec[0];
}
T& x()
{
   return myVec[0];
}