How can I avoid writting and maintaining the same code in the two operator
[] implementation below? I know that in the minimal example below, the
implementation is trivial, but I found this type of problem (maintaining two
function overloads one const and one not const - having the same body), many
times...
Thanks,
Romulus
#include <iostream>
class SomeClass
{
public:
int & operator[](int index)
{
return array[index];
}
const int & operator[](int index) const
{
return array[index];
}
protected:
// internal data
int array[10];
};
void func(const SomeClass & sc, int index)
{
std::cout << sc[index] << std::endl;
}
void main(void)
{
SomeClass c;
c[3] = 5;
func(c, 3);
}
[] implementation below? I know that in the minimal example below, the
implementation is trivial, but I found this type of problem (maintaining two
function overloads one const and one not const - having the same body), many
times...
Thanks,
Romulus
#include <iostream>
class SomeClass
{
public:
int & operator[](int index)
{
return array[index];
}
const int & operator[](int index) const
{
return array[index];
}
protected:
// internal data
int array[10];
};
void func(const SomeClass & sc, int index)
{
std::cout << sc[index] << std::endl;
}
void main(void)
{
SomeClass c;
c[3] = 5;
func(c, 3);
}
Comment