How do I define a function in a class template?

T

Tomás

template <class T>
class Monkey {

int Eat();
};

int Monkey::Eat()
{
return 5;
}


This won't compile. In what way have I defined the function wrongly? Are
you supposed to write them like this?:

template <class T>
class Monkey {

int Eat();
};

template <class T>
int Monkey<T>::Eat()
{
return 5;
}


It seems a bit pedantic to me that you have to that...

-Tomás
 
T

Tomás

It seems a bit pedantic to me that you have to that...


Opps I read over my post there and it sounded like I was being sarcastic.

Really, I want to know how to do this properly.

I'll have to get Bjarne's book out of the library again... I used to know
all this stuff about a year ago!

Any help appreciated.

-Tomás
 
V

Victor Bazarov

Tomás said:
Opps I read over my post there and it sounded like I was being sarcastic.

Really, I want to know how to do this properly.

I'll have to get Bjarne's book out of the library again... I used to know
all this stuff about a year ago!

You did it right. Your 'Eat' member is _private_ in your class template
'Monkey', so it cannot be used by anybody.

V
 
O

osmium

Tomás said:
Opps I read over my post there and it sounded like I was being sarcastic.

Really, I want to know how to do this properly.

I'll have to get Bjarne's book out of the library again... I used to know
all this stuff about a year ago!

Any help appreciated.

Help doing what? You have a compiler, do you not? Why not try the second
way? If there are problems fix them.. Try adding public:. It not only
looks right, it works for me. What more do you want?
 

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

Forum statistics

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

Latest Threads

Top