Boost logo

Boost :

From: Navi Singh (singh_at_[hidden])
Date: 2002-07-18 15:32:46


 Peter Dimov:

 I am probably talking thru my hat. Don't know all the issues involved, but
 here is a suggestion. Is the following a bad idea? If not, is it feasible
 to provide a such a functionality in your smart ptr library.

 Consider two classes, one derives from counted base and one doesn't.
 class test1
 {
 };
 class test2 : public boost::counted_base
 {

 };

 As a rule, everyone will use a ptr template (defined later in this post).
 The ptr template will either be a shared_ptr or an intrusive_ptr template
 based on whether the class in consideration derives from counted_base or
 not.

 ptr<test1> t1(new test1); // ptr is a shared_ptr.
 ptr<test2> t2(new test2); // ptr is an intrusive ptr.

 This is stolen from code that Andrei posted on the net and modified to
suit.
 =======================================

 template< bool flag, class True, class False >
 struct If // Andrei's Select template
 {
  template<bool flag>
  struct _Select{
   typedef True result;
  };
  template<>
  struct _Select<false>{ // specialization for false.
   typedef False result;
  };
  typedef _Select<flag>::result Result;
 };
 template <class Candidate, class Base>
 class Inheritance
 {
  static int IsDerived(Base *); // invoked for all Candidates derived from
 Base
  static char IsDerived(...); // invoked for anything, but lower
 precedence than above.
 public:
  enum { IsDerivedFromBase = sizeof(IsDerived((Candidate *)0)) ==
 sizeof(int) };
 };

 template<class T, bool b = (Inheritance<T,
 boost::counted_base>::IsDerivedFromBase) >
 class Ptr : public If<b, boost::intrusive_ptr<T >, boost::shared_ptr<T >
>::Result
 {
  typedef boost::intrusive_ptr<T > intrusiveT;
  typedef boost::shared_ptr<T > sharedT;
  typedef If<b, intrusiveT, sharedT >::Result baseT;
 public:
  // inline ~Ptr(){}
  inline Ptr():baseT(){}
  inline Ptr(baseT *x):baseT(x){}
  inline Ptr(const baseT& x):baseT(x){}
  inline baseT& operator=(const baseT& x){return baseT::operator=(x);}
  inline baseT& operator=(baseT *x){return baseT::operator=(x);}

  // inline operator T*() const {return baseT::operator*();}
  // inline T *operator->() const{return baseT::operator->();}
 //...
 //...
 // not sure what all needs to be here.
 //...
 };


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk