more template problem

T

Tony Johansson

Hello!

I have some problem with template.

I have two classes called Handle which is a template class and Integer which
is not a template class. The Integer class is just a wrapper class for a
primitive int with some methods. I don't show the Integer class because it
will not add any information to my problem.

Now to my problem in the handle class I have an operator defined as
T* operator&() const
{ return body;
This returns the pointer value for body. But the symbol & is not so
understandable for a pointer.
So why can't I use symbol -> instead of the symbol & in the operator
function like
T* operator->() const
{ return body; }

If I do that I get the following compile error c:\Documents and
Settings\Tony\kau\cplusplus\lab4_c++\start.cpp(19): error C2059: syntax
error : '->'

I meant that using statements like Integer* tt = ->myh2;
will set pointer tt to the same pointer value as body.
On the other hand it might not be so suitable to use the symbol -> because
the syntax seams
strange when there is only one operand.

What symbol is most suitable to use for returning a pointer object from
class Handler.
What I mean is what symbol should be put in instead for ? in the operator
below.
T* operator?() const
{ return body; }
to make it most understandable.

Have you any suggestion ?


//Tony


#include "handle.h"
#include <list>
#include <algorithm>
using namespace std;
typedef Handle<Integer> handle_t;

main()
{
list<handle_t> myList1;
handle_t myh1( new Integer(1) );
handle_t myh2( new Integer(2) );
}

#include "integer.h"
#include <iostream>
using namespace std;

template<class T>
class Handle
{
public:

Handle(T* body_ptr) //Constructor
{ body = body_ptr; }

T* operator&() const
{ return body;

private:
T* body;
};
 
C

christopher diggins

Hi Tony,

Three ways I can think of:

1)

template<class T>
class Handle
{
...
T& operator*()
{ return *body; }
...
};

Handle<T> x;
T* p = &*x;

or
2)

template<class T>
class Handle
{
...
T* operator T*()
{ return body; }
...
};

Handle<T> x;
T* p = x;

or my personal preference
3)

template<class T>
class Handle
{
...
T* get_raw_pointer() // some prefer simply "get"
{ return body; }
...
};

Hope this helps
-Christopher Diggins
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,815
Latest member
treekmostly22

Latest Threads

Top