Possible Duplicate:
How do I remove code duplication between similar const and non-const member functions?
In the following example :
template<typename Type, unsigned int Size>
class MyClass
{
public: inline Type& operator[](const unsigned int i)
{return _data[i];}
public: inline const Type& operator[](const unsigned int i) const
{return _data[i];}
protected: Type _data[Size];
};
the const and non-const operator[]
are implemented independently.
In terms of design is it better to have :
If solution 2) is better, what would be the code of the given example ?
You couldn't have either implementation calling the other one without casting away constness, which is a bad idea.
The const
method can't call the non-const
one.
The non-const
method shouldn't call the const
one because it'd need to cast the return type.