template

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
Integer operator*() const
{ return *body; }
but I want to defined it in the template way which is
Handle<T> operator*() const
{ return *body; }
when I do that I get the compile error c:\Documents and
Settings\Tony\kau\cplusplus\lab4_c++\start.cpp(10): error C2440:
'initializing' : cannot convert from 'Handle<T>' to 'Integer' with [
T=Integer ]

I want to use the type name Handle<T> in the Handle class instead of the
Integer class name.

Have you any suggestion how to solve my problem?


//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; }

Integer operator*() const
{ return *body; }

private:
T* body;
};
 
K

Kai-Uwe Bux

Tony Johansson wrote:

[snip]
#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; }

Integer operator*() const
{ return *body; }

private:
T* body;
};

As you can see, body is of type T* and therefore any method that returns
*body, better have return type T, T const &, or T&. I.e., what about:

template<class T>
class Handle
{
public:

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

T const & operator*() const
{ return *body; }

private:
T* body;

};
 

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

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top