Here’s a set of C++ classes which implement a kind of adapter pattern:
#include <iostream>
class Cfoo
{
public:
explicit Cfoo(int i):i_(i){}
void SetI(int i){ i_ = i; }
int GetI()const{ return(i_); }
private:
int i_;
};
class CfooHolderConst
{
public:
explicit CfooHolderConst(const Cfoo& foo):foo_(foo){}
int GetI()const{ return( foo_.GetI() ); }
private:
const Cfoo& foo_;
};
class CfooHolderNonConst
{
public:
explicit CfooHolderNonConst(Cfoo& foo):foo_(foo){};
int GetI()const{ return( foo_.GetI() ); }
void SetI(int i){ foo_.SetI(i); }
private:
Cfoo& foo_;
};
int main( int argc, char* argv[] )
{
const Cfoo myConstFoo(42);
CfooHolderConst myConstFooHolder(myConstFoo);
std::cout << myConstFooHolder.GetI() << std::endl;
Cfoo myNonConstFoo(1);
CfooHolderNonConst myNonConstFooHolder(myNonConstFoo);
myNonConstFooHolder.SetI(42);
std::cout << myConstFooHolder.GetI() << std::endl;
return(0);
}
I want to combine CfooHolderNonConst and CFooHolderConst into a single class, or failing that, inherit one from the other. The reference to Cfoo is a problem here, because in CFooHolderConst it needs to be defined as const Cfoo&, while in CfooHolderNonConst it needs to be Cfoo&.
This is a similar problem to the interator/const_iterator here:
How to avoid code duplication implementing const and non-const iterators?
…but I’m hoping that because this doesn’t have to meet the STL iterator requirements, there might be a simpler solution.
In the past I’ve solved this kind of problem by having both a const and nonconst pointer as class members, and setting one or the other up from overloaded constructors. This wastes space and seems clumsy. Is there a more elegant solution?
Yes, it can be done:
Actually this is intended to be an example where you wrap the getting of the underlying data in its const or non-const state. The Reader holds a non-const reference unless the templated type is const, but doesn’t let you write to it, so you can extend it as with CHolderReaderWriter when you do need to write to it.