How can I allow a non-const reference to convert to a const reference in a wrapper template copy constructor? Note that my copy constructor is a logical move constructor (pre-C++11) — the init member tracks which wrapper is currently valid.
template<typename T>
class wrap
{
T & object;
bool init;
public:
wrap( T& object ) : object(object), init( true ) { }
//attempt which fails since "init" is private in other type
template<typename O>
wrap( wrap<O> const & o )
: object( o.object )
, init( true )
{
const_cast<wrap<O>&>(o).init = false;
}
};
This works fine if the other type is exactly the same, since then access rules allow access to the private init variable. Basically, the following should work:
//adding const
wrap<Type> a( get() );
wrap<Type const> b = a;
//base type would also be nice
wrap<BaseType> c = a;
Befriend other specialisations:
or for better encapsulation, just their conversion constructors:
It would be better to declare
initmutable; usingconst_cast, there’s a risk of undefined behaviour if anyone tries to copy aconstobject.Also, be aware that your constructor template won’t overload the implicitly generated copy constructor. You’ll also need a copy constructor to do the right thing with
init: