Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding repetition of const and non-const version of getters?

struct BananaHolder
{
    vector<Banana>& getBananas();
    const vector<Banana>& getBananas() const;
};

My classes are cluttered with this kind of duplication.

Is there a cleaner, more elegant alternative?

like image 967
Vittorio Romeo Avatar asked Sep 13 '25 20:09

Vittorio Romeo


1 Answers

If your class has to return references, and if it has to return a reference to a modifiable vector when invoked on a modifiable object, then I do not think there is a way to avoid the duplication - at least, not the duplicate declaration.

Notice, that some types of the Standard Library also suffer from the same problem. For instance, sequence containers such as std::vector have both a const and a non-const overload of operator [], at(), back(), front(), data(), and so on.

like image 157
Andy Prowl Avatar answered Sep 15 '25 11:09

Andy Prowl