Subject: boost mpl question: best way to remove pointer in template class
From: [email-masked] (bigfaceworm)
Date: 9 May 2004 09:27:56 -0400
Newsgroups: comp.lang.c++.moderated

All,

I'm a beginner here, and am trying to do a relatively simple task (as
far as MPL is concerned).  I finally solved a simple case, but I don't
think it's the proper solution in general.

Basically, I'm going to write a template class to operate on a class
T.  It expects T to conform to a interface.  In my simple case - it
only requires a method 'hi()'.

Now, what I'd really like is for my template class to be able to
operate on T regardless of whether or not it's a pointer, a reference,
a const reference, etc.

And I don't want to have to write code (that obviously doesn't work) like:

    if (boost::is_pointer<T>::value) {
      t->hi();
    }
    else {
      t.hi();
    }

I've attached a simple example that works (well, haven't checked const
yet), but would appreciate feedback - or a pointer to an
implementation that already does the trick.  Compiles and runs in gcc3.2.

And secondly, what traits does a class have to have to be considered a
pointer?  i.e. that satisfies

    BOOST_STATIC_ASSERT(boost::is_pointer<T>::value);

Just thinking about working with auto_ptr, boost::smart_ptr,
user-defined-pointer-type etc.

many thanks,

BFW

---------------------------------------------------------
struct SayHi
{
   void hi()
   {
     cout << "Saying hi" << endl;
   }

};

template <class T>
struct Blah {
   typedef typename boost::remove_pointer<T>::type T_type;
   typedef typename boost::add_reference<T_type>::type T_reference;
   typedef typename boost::add_pointer<T_type>::type T_pointer;

   T_reference remove_pointer(T_reference t)
   {
     return t;
   }

   T_reference remove_pointer(T_pointer t)
   {
     return *t;
   }

   Blah(T t) {
     remove_pointer(t).hi();
   }
};

// these work, yay.
SayHi hi;
Blah<SayHi> b(hi);
Blah<SayHi*> bptr(&hi);
Blah<SayHi&> bref(hi);

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]