Let's say I have a class like this:
class LinkedList
{
struct Node
{
int StoredValue;
// ...
};
Node& GetNodeReference(std::size_t Index)
{
// ...
return NodeReference;
}
public:
int Get(std::size_t Index) const
{
return GetNodeReference(Index).StoredValue;
}
};
This won't compile because the const method Get uses GetNodeReference, which cannot be const because it returns a reference.
How can I work around this?
I'm not sure what you're trying to achieve, but you could provide two overloads of
GetNodeReference:Note that the second overload has two
constmodifers, one at the beginning of the line for the return type and one at the end of the line for the implicitly passed*thisobject.To avoid code repetition, you can implement the non-const overload based on the const overload:
This technique is discussed in Item 3 of Effective C++ by Scott Meyers.