c++ - Are there any alternatives to making const version of class? -
c++ - Are there any alternatives to making const version of class? -
in c++ i'm facing situation when need prepare const , non-const version of class in analogy const_iterator , iterator standard library.
class const_myclass { public: const_myclass(const int * arr): m_arr(arr) { } int method() const; //does m_arr without modifying private: const int * m_arr; } class myclass { public: myclass(int * arr): m_arr(arr) { } int method() const; //does m_arr without modifying void modify(int i); //modify m_arr private: int * m_arr; }
the problem need repeat whole code of const_myclass
in myclass
, distribute changes in api both classes. inherit const_myclass
, const_casts, isn't perfect , pretty solution. still when want pass const_myclass
instance reference looks moronic:
void func(const const_myclass & param)
instance param marked 2 "consts", , has const methods...
this const constructors handy, there existing alternatives?
some utilize examples explain problem better:
//ok modify info void f(int * data) { myclass my(data); my.modify(); ... } //cant modify data, cant utilize myclass void fc(const int * data) { const_myclass my(data); int = my.method(); ... }
you can create template class deed base, this:
template<typename t> class basic_myclass { public: basic_myclass(t * arr) :m_arr(arr) {} int method() const; //does m_arr without modifying private: t * m_arr; };
then, const version, since doesn't add together anything, can utilize typedef
:
typedef basic_myclass<const int> const_myclass;
for non-const version, can inherit:
class myclass : public basic_myclass<int> { public: using basic_myclass::basic_myclass; // inherit constructors void modify(int i); //modify m_arr };
c++ const-correctness
Comments
Post a Comment