[Boost-users] Help with custom smart pointer const correctness
Dominique Devienne
15 Apr
2009
15 Apr
'09
9:16 p.m.
Given the class design below, and the ObjectPtr smart pointer
implementation, I can't instantiate ObjectPtr<T> with T = const Car
because a const Car returns a shared_ptr<const CarIdent> from the
ident() methods, not a shared_ptr<CarIdent> as currently implemented
(see compile error at the end of this post. VS2005).
From my very limited meta-programming experience, I'm guessing I need
to fix the current typedef shared_ptr ident_ptr; in
ObjectPtr to somehow use MPL to "return" shared_ptr<typename
T::ident_type const> given a const T, and shared_ptr<typename
T::ident_type> given a T, but I don't know how to do that yet.
If someone would be kind enough to point me in the right direction,
I'd appreciate. Thanks, --DD
#include
#include
#include
#include
#include <string>
using namespace std;
using namespace boost;
class Object;
class Ident {
public:
Object* object() const { return object_; }
protected:
Ident() : object_(0) {}
~Ident() {}
friend class Object;
void set_object(Object* e);
private:
Object* object_;
};
typedef shared_ptr<Ident> IdentPtr;
typedef shared_ptr<const Ident> ConstIdentPtr;
class Object {
public:
ConstIdentPtr ident() const { return ident_; }
const IdentPtr& ident() { return ident_; }
protected:
Object(shared_ptr<Ident> ident) : ident_(ident) {
ident_->set_object(this); }
virtual ~Object() { ident_->set_object(0); }
private:
shared_ptr<Ident> ident_;
};
void Ident::set_object(Object* obj) {
BOOST_ASSERT((!object_ && obj) || (object_ && !obj));
BOOST_ASSERT(!obj || obj->ident().get() == this);
object_ = obj;
}
template <class T> shared_ptr<typename T::ident_type> ident_of(T* t) {
BOOST_STATIC_ASSERT((is_base_of