a wrote:[color=blue]
> Hi,
>
> I'm trying to create a helper class that will allow me to use a pointer or
> reference to a class without knowing if it is a pointer or reference.
>
> Conceptual example:
>
> //******************
> // class B has one public method f
> class B
> {
> public:
> void f()
> {
> }
> };
>
> // use a fictional class A to do the following
>
> B b;
> B* pb = &b;
>
> A<>( b ).f();
> A<>( pb ).f();
> //*********************
>
> What this should do is regardless of whether the A constructor receives a
> pointer or reference to B, and without having to specify the actual type in
> the template argument list, it will be able to call the method f in the same
> fashion, using the . operator in this example (or it could be ->)
>
> Here is my attempt at this, using 2 specialized member functions for
> reference and pointer types - see my comments below.
>
> //*******************
> // helper class A
>
> template< typename T > class A
> {
> private:
> T _t;
>
> public:
> A( T t )
> : _t( t )
> {
> }
>
> void f()
> {
> }
> };
>
> // specialized method that works for references to B
> template<> inline void A< B& >::f()
> {
> return _t.f();
> }
>
> // specialized method that works for pointers to B
> template<> inline void A< B* >::f()
> {
> return _t->f();
> }
> //****************
>
> This doesn't work the way I intended. In order for it to work, I have to
> specify the argument type in the template argument list, which defeats the
> purpose of having this automatically done by the compiler.
>
> A<B&>( b ).f();
> A<B*>( pb ).f();
>
> I was expecting that the compiler would be capable of determining the
> template argument type from the type of the value passed to the constructor
> (b, or pb).
>
> I would appreciate any help or ideas on this.
>[/color]
I'm not sure if this is what you're looking for, but check out the
following class:
template<typename T>
class ZeroMemorySafe
{
private:
template <typename TT> struct deref_t {typedef TT type_t;};
template <typename TT> struct deref_t<TT*> {typedef typename
deref_t<TT>::type_t type_t;};
public:
typedef typename deref_t<T>::type_t ref_t;
typedef T type_t;
void operator()(ref_t &t)
{
ZeroMemory(&t, sizeof(t));
}
void operator()(ref_t *t)
{
ZeroMemory(t, sizeof(*t));
}
};
I use the above class with the following function:
template<class T>
void ZeroMemoryT(T& t)
{
ZeroMemorySafe<T>()(t);
}
Which allows the above function to work with pointer types, and
reference type.
----------------------------------------------------------------------------------------
David Maisonave
http://axter.com
Top ten member of C++ Expert Exchange:
http://www.experts-exchange.com/Cplusplus
----------------------------------------------------------------------------------------